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编码才可以使用。