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

6 篇文章 0 订阅

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]

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值