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

原文链接:http://www.juzicode.com/archives/2493

错误提示:

打开文件路径提示参数无效: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 <module>
    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)

回答: 出现OSError: [Errno 22 Invalid argument错误的原因是在调用open函数时传入了一个带有特殊字符的文件名。Python的strip()函数只能去除字符串首尾的空格,无法去除中间的空格,需要使用replace()函数来替换中间的空格。另外,\r代表回车,即打印头归位,而\n代表换行。如果想要去除字符串中的空格、换行和回车,可以使用replace()函数来处理。至于python打包成exe文件出现OSError: [Errno 22 Invalid argument错误,可能是因为exe文件的输入参数不正确,请检查你的代码中是否存在传入带有特殊字符的参数。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python文件操作错误:OSError: [Errno 22] Invalid argument(关于Windows下文件名中的敏感字符)](https://blog.csdn.net/m0_54490473/article/details/122706256)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [python中文件保存时,出现OSError:[Errno 22] Invalid argument解决办法](https://blog.csdn.net/bbrry/article/details/125690638)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值