我有以下文件结构:
test/
test1.py
test2.py
text.txt
Run Code Online (Sandbox Code Playgroud)
以下是文件的内容
test1.py:
import sys
sys.path.append('../')
import test2
test2.read()
Run Code Online (Sandbox Code Playgroud)
test2.py:
def read():
with open('text.txt', 'rb') as f:
print f.read()
if __name__ == "__main__":
read()
Run Code Online (Sandbox Code Playgroud)
text.txt包含一行文字.当我运行时test1.py,我收到"找不到文件"错误:
Traceback (most recent call last):
File "test1.py", line 5, in <module>
test2.read()
File "../test2.py", line 2, in read
with open('text.txt', 'rb') as f:
IOError: [Errno 2] No such file or directory: 'text.txt'
Run Code Online (Sandbox Code Playgroud)
我有点理解为什么会出现这个错误.但是我该如何处理这些错误呢.我希望代码test2.py就像我可以在任何地方使用的库代码.
sys.path用于python路径(PYTHONPATHeviroment变量).即当你在import某些库时,在哪里寻找python 库.它不会影响在哪里open()寻找文件.
当你open(filename).在filename相对于procees 工作目录.(代码运行的路径)
因此,如果要访问其路径相对于代码文件路径的flie,则可以使用__file__包含当前文件路径的builtin变量.
所以你可以改为test2.py:
import os
def read():
with open(os.path.join(os.path.dirname(__file__),'text.txt'), 'rb') as f:
print f.read()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
438 次 |
| 最近记录: |