作者rebellionyu (Rebellionyu)
看板Python
標題[問題] Import module to open file
時間Thu Feb 9 11:03:22 2017
最近遇到一個import問題,雖然可以解決,
但想知道比較普遍或python通常怎麼做。
資料夾結構如下:
package
|__main.py
|__module
|__output.py
|__display.txt
在package資料夾裡有main.py及module資料夾,
module資料夾裡有output.py, display.txt兩個檔案。
============================
main.py內容為:
from module.output import *
printFile()
============================
output.py內容為:
def printFile():
f = open('display.txt', 'r')
print(f.read())
f.close()
若我直接執行python main.py會顯示找不到display.txt這個檔案。
雖然在開檔時可以直接利用os這個module來產生絕對路徑。
像是:path = os.path.join(os.path.abspath(__file__), 'display.txt')
但我總覺得這樣相當難看。
請問有比較好的作法嗎?或是就真的如上,必須產生絕對路徑讀檔。
謝謝各位!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.219.202.66
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1486609405.A.577.html
推 s860134: 你的方法應該就是最佳解吧 02/09 12:21
→ Neisseria: 包在內部沒差,外部使用的人不需要處理這些細節 02/09 12:22
→ s860134: 你找不到txt 是因為你的當前路徑並不是在這個檔案目錄 02/09 12:24
→ rebellionyu: 好,謝謝各位的回答! 02/09 12:32
→ zerof: _ROOT = os.path.dirname(os.path.abspath(__file__)) 02/09 12:47
→ zerof: def printFile(dir=_ROOT): 02/09 12:48
→ zerof: with open(os.path.join(dir, "display.txt"), 'r') as f 02/09 12:49