错误提示:
打开文件路径提示参数无效: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'
错误原因:
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)
关注微信公众号:“桔子code”,欢迎后台留言撩我,我会尽我所能为你解惑Python,C等编程知识