我在這個結構我的Python代碼:Python的路徑沒有找到文本文件
folder:
Procfile
folder2:
myprog.py
foo.py
somefile.txt
我Procfile
包含web: python folder2/myprog.py
myprog.py
包含:
import sys
sys.path.insert(0, '../')
#other code
foo.py
包含:
print "about to read file"
file = open("somefile.txt", "r")
print file.read()
print "done reading"
我無法讀取文件。該代碼從未達到done reading
部分儘管它已經打印about to read file
它會拋出一個錯誤嗎? 'sys.path.insert('..')'是添加模塊路徑搜索('import xyz')'的一個技巧,而不是用於打開普通文件。 – Anthon
用'try/catch'圍繞它後,我得到這個錯誤'I/O錯誤(2):沒有這樣的文件或目錄' – Anthony
我不認爲它試圖打開文件,你認爲它試圖打開它。在這之前嘗試'print os.getcwd()'(並確保你有一行'import os')來查看你的目錄。我的猜測是你需要做'file = open(「folder2/somefile.txt」)' – Anthon