python写入文件时报错IOError: [Errno 22] invalid mode ('w') or filename: '\xe7\xac\xac1\xe9\xa1\xb5.html'

本文介绍了一种在Python 2.7环境下使用PyCharm进行网页爬虫时遇到的文件写入错误,并提供了将文件名转换为Unicode编码的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python写入文件时报错IOError: [Errno 22] invalid mode (‘w’) or filename: ‘\xe7\xac\xac1\xe9\xa1\xb5.html’

python的版本是2.7,在win10下运行的pycharm

写入的是一个网页信息,HTML数据,结果报错为
Traceback (most recent call last):
File “E:/pythonѧϰ/pachong/tieba.py”, line 56, in
tiebaSpider(fullurl, beginPage, endPage)
File “E:/pythonѧϰ/pachong/tieba.py”, line 45, in tiebaSpider
writePage(html, filename)
File “E:/pythonѧϰ/pachong/tieba.py”, line 27, in writePage
with open(filename, “w”) as f:
IOError: [Errno 22] invalid mode (‘w’) or filename: ‘\xe7\xac\xac1\xe9\xa1\xb5.html’
问过别人之后把代码修改为:
with open(filename.decode(“utf-8”), “w”) as f:
f.write(html)
这样就可以了,在open(filename,“w”)中,filenam必须使用unicode编码才可以使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值