Python 找不到文本文件的路径
Python path not finding text file
我的 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
您可以利用自动模块变量 __file__
并且您知道 somefile.txt
与 foo.py
在同一目录中:
file = open(os.path.join(os.path.dirname(__file__), "somefile.txt"), "r")
sys.path
仅确定导入模块的搜索路径,而不是从文件系统打开通用文件的位置。
我的 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
您可以利用自动模块变量 __file__
并且您知道 somefile.txt
与 foo.py
在同一目录中:
file = open(os.path.join(os.path.dirname(__file__), "somefile.txt"), "r")
sys.path
仅确定导入模块的搜索路径,而不是从文件系统打开通用文件的位置。