天天看点

with open(filename,"w")as f: IOError: [Errno 22] invalid mode ('w') or filename

#这样写不用做文件关闭操作,就是一个文件写入操作
    with open(filename,"w")as f:
        f.write(html)
           

出现问题:

File "F:/pycrawler/venv/tieba.py", line 28, in writePage
    with open(filename,"w")as f:
IOError: [Errno 22] invalid mode ('w') or filename: '\xe7\xac\xac1\xe9\xa1\xb5.html'
           

问题出现原因:

open(filename, ‘w’)这个方法中,filename这个参数必须是Unicode编码的参数

头文件有

#-*-coding:utf-8-*-

将编码设置为utf-8,当调用这个方法往里传参数时,需要将这个变量编码转换为Unicode

解决问题:

转码

with open(filename.decode('utf-8'),"w")as f:
        f.write(html)