python解释器是在与脚本所在的目录不同的目录下执行时出错的例子:
(tensorflow) [root@localhost python]# cat test.txt
a
b
c
同目录py文件:
(tensorflow) [root@localhost python]# cat sto.py
with open('test.txt', 'r') as f:
for line in f:
print(line)
退回上级目录:
cd..
运行sto.py文件:
(tensorflow) [root@localhost vagrant]# python ./python/sto.py
Traceback (most recent call last):
File "./python/sto.py", line 1, in <module>
with open('test.txt', 'r') as f:
IOError: [Errno 2] No such file or directory: 'test.txt'
解决方法:用os把当前目录加入系统路径中:
(tensorflow) [root@localhost python]# vim sto.py
import os
MYDIR = os.path.dirname(__file__)
with open(os.path.join(MYDIR, 'test.txt')) as f:
for line in f:
print(line)
再次运行:
(tensorflow) [root@localhost vagrant]# python ./python/sto.py
a
b
c