UnicodeEncodeError: 'gbk' codec can't encode character '\xb9' in position 0: illegal multibyte seque

python学习笔记,复制文件内容时报错

将test.txt的内容复制到test1.txt中
test.txt的内容如图所示:
UnicodeEncodeError: 'gbk' codec can't encode character '\xb9' in position 0: illegal multibyte seque_第1张图片
方法1:使用with
encoding=“ISO-8859-1” 正常

in_file=input("需要拷贝的文件是:")
with open(in_file,'r+',encoding="ISO-8859-1") as file:
	file.truncate(3)
	indata=file.read()
	 

out_file=input("复制到(输入文件名):")
with open(out_file,'w+',encoding="ISO-8859-1")as file:
	file.write(indata)
	file.seek(0)
	outdata=file.read()
	  
print(indata==outdata)

在这里插入图片描述
encoding="UTF-8"报错
UnicodeEncodeError: 'gbk' codec can't encode character '\xb9' in position 0: illegal multibyte seque_第2张图片
encoding="gbk"报错
UnicodeEncodeError: 'gbk' codec can't encode character '\xb9' in position 0: illegal multibyte seque_第3张图片
方法二:直接复制

in_file=open("test.txt",encoding="gbk")    #只读模式打开文件
indata=in_file.read()

out_file=open("test1.txt",'w')    #用‘w’打开复制的文件 to_file
out_file.write(indata)

运行结果:
直接复制文件内容

你可能感兴趣的:(python)