在进行ben办法学Python习题17时,遇到问题,请教如何解决。
代码如下。
# -*- coding: utf-8 -*-
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
# We could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()
print (f"The input is {len(indata)} bytes long")
print (f"Does the output file exist?{exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
out_file = open(to_file, 'w')
out_file.write(indata)
print("Alright, all done.")
out_file.close()
in_file.close()
报错形式如下:
PS C:\Users\Suning> python ex17.2.py test.txt test1.txt
Copying from test.txt to test1.txt
Traceback (most recent call last):
File "C:\Users\Suning\ex17.2.py", line 11, in <module>
indata = in_file.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence
PS C:\Users\Suning>
test.txt 这个文件的编码是什么? 你打开这个文件另存为的时候编码看下,最好修改成utf-8就能使用默认的这种方式,不然就要按编码类型添加打开文件的方式
在in_file = open(from_file)中添加编码方式,写成in_file = open(from_file,'r',encoding='utf-8'),同样在后面写入文件时,在open中,也要加入指定编码参数。