将test.txt的内容复制到test1.txt中
test.txt的内容如图所示:
方法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"报错
encoding="gbk"报错
方法二:直接复制
in_file=open("test.txt",encoding="gbk") #只读模式打开文件
indata=in_file.read()
out_file=open("test1.txt",'w') #用‘w’打开复制的文件 to_file
out_file.write(indata)