python运行py文件参数错误_Python错误集锦:打开文件路径提示参数无效,OSError: [Errno 22] Invalid argument: ‘D:\juzicode\桔子code\r...

错误提示:

打开文件路径提示参数无效:OSError: [Errno 22] Invalid argument: ‘D:\juzicode\桔子code\readme.txt’

D:\juzicode>python read_file.py

Traceback (most recent call last):

File "read_file.py", line 4, in

fileobj=open(filename,'r',encoding='utf-8')

OSError: [Errno 22] Invalid argument: 'D:\\juzicode\\桔子code\readme.txt'

8eafa521541f315700b2ef4d22cc6b7d.png

错误原因:

1、py文件第3行,filename中使用了单个”\”会引起转义,解释器认为“\”和后面紧邻的一个字符组合成一个字符,而组合出来的字符是非法的,所以报错了参数无效。

解决方法:

1、在包含“\”的字符串前加字母r前缀,filename=r’D:\juzicode\桔子code\readme.txt’:

filename=r'D:\juzicode\桔子code\readme.txt'

fileobj=open(filename,'r',encoding='utf-8')

filecont = fileobj.read()

print(filecont)

2、在文件路径中使用连续2个斜杠:

#juzicode.com

#微信公众号: 桔子code

filename='D:\\juzicode\\桔子code\\readme.txt'

fileobj=open(filename,'r',encoding='utf-8')

filecont = fileobj.read()

print(filecont)

3c824dc7733195306f380137f7cab94c.png

关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识

5dbcc3c426b20162f171885f8fc3ed5e.png

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值