Python - IOError: No such file or directory: u'...'问题解决

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

参考:[https://stackoverflow.com/questions/27975415/python-ioerror-errno-2-no-such-file-or-directory-ulastid-py-for-file-in]

猜你喜欢

转载自blog.csdn.net/nockinonheavensdoor/article/details/80061231