Python版本为2.7.0,IDE为PyCharm
f = open(filename, 'w')
f.write(html)
filename中包含中文,html为一个网页数据,结果报了如下的错
File "D:/PythonWorkSpace/test.py", line 42, in <module>
tiebaSpider(fullUrl,beginPage,endPage)
File "D:/PythonWorkSpace/test.py", line 31, in tiebaSpider
writeFile(html,filename)
File "D:/PythonWorkSpace/test.py", line 20, in writeFile
f = open(filename, 'w')
IOError: [Errno 22] invalid mode ('w') or filename: '\xe7\xac\xac1\xe9\xa1\xb5.html'
将代码修改为:
f = open(filename.decode('utf-8'), 'w')
f.write(html)
成功运行,因为是Python中的字符串的大概分为为str和Unicode两种形式,其中str常用的编码类型为utf-8,gb2312,gbk等等,Python使用Unicode作为编码的基础类型,open(filename, ‘w’)这个方法中,filename这个参数必须是Unicode编码的参数。
本文详细解析了在Python 2.7环境下,使用PyCharm进行文件写入操作时遇到的IOError问题,深入探讨了错误原因在于文件名编码不匹配,并提供了有效的解决方案,即通过decode('utf-8')转换文件名为Unicode编码。
3129

被折叠的 条评论
为什么被折叠?



