UnicodeDecodeError:'gbk' codec can't decode byte 0x94 in position 162: illegal multibyte sequence

需求:把指定目录下的文件复制到当前目录命名为copy

在处理文件复制过程中,出现以下报错
‘gbk’ codec can’t decode byte 0x94 in position 162: illegal multibyte sequence

with open('D:\sample.txt','r+') as f1:
    with open('D:\copy.txt','w+') as f2:
        f2.write(f1.read())

UnicodeDecodeError: 'gbk' codec can't decode byte 0x94 in position 162: illegal multibyte sequence

分析:该报错理解为‘gbk’解码器无法解析字节,那么问题就可以定位在字节编码上

思路1
指定文件sample.txt写入时的编码(gbk、unicode、utf-8),只能挨个测试,我的文件在测试到utf-8时成功写入

with open('D:\sample.txt','r+',encoding='utf-8') as f1:
    with open('D:\copy.txt','w+',encoding='utf-8') as f2:
        f2.write(f1.read())

思路2
因为不知道文件写入时的编码,挨个测试效率极低,有没有忽略编码打开的方式呢?
在内存中,无论什么编码最终都会转换为二进制进行存储,所以文件以二进制方式打开就不会有编码的问题了

with open('D:\sample.txt','rb+') as f1:
    with open('D:\copy.txt','wb+') as f2:
        f2.write(f1.read())

你可能感兴趣的:(python基础)