有时候正常没有问题的程序会报错,可能跟注释里面的中文也有关系
1 with open('photo1.jpg','rb') as file: 2 data = file.read() 3 #print(data) 4 with open('photo5.jpg','wb') as newfile: 5 newfile.write(data)
这个代码是没有问题的
1 with open('photo1.jpg','rb') as file: 2 data = file.read() 3 #print(data) 4 with open('photo2.jpg','wb') as newfile: # 以“wb”模式写入 5 newfile.write(data)
这样就会报错了
1 # coding=gbk 2 with open('photo1.jpg','rb') as file: 3 data = file.read() 4 #print(data) 5 with open('photo10jpg','wb') as newfile: # 以“wb”模式写入 6 newfile.write(data)
这样就又好了
程序中出现中文,运行的时候出现如下错误:
SyntaxError: Non-UTF-8 code starting with 'xc1' in file C:...xxx.py on line 8, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
导致出错的根源就是编码问题。
解决方案是:
在程序最上面加上:
# coding=gbk
这样程序就可以正常运行了。