这是在《Learn Python3 The Hard Way》的第17个练习中出现的问题,Python文件的代码如下:
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 file 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()
根据这本书的操作,先用Powershell用命令行创建一个文本并在里面写一些内容,命令行如下:
echo "想要在文本里面写入的内容" > test.txt
然后按正常操作运行程序,结果出下以下的报错:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence
然而,如果是自己手动新建一个test.txt文本文件并在里面写入内容的话,则不会出现报错。所以,猜测应该是利用Powershell创建文本写入内容的编码应该是和手动新建的编码不一样,而用Powershell创建的文本内容的编码在默认情况下是不能被Python识别的,所以,如果想正确读取用Powershell创建的文本,需要对读入内容的编码进行修改:
第9行:in_file = open(from_file,'rb')
第18行:out_file = open (to_file, 'wb')
之后程序便可正常运行。