我正在尝试打开并重排包含大量文本的.txt文件。下面是我的代码,我不知道如何解决这个问题。任何帮助都将不胜感激。
file = input("Please enter a .txt file: ")
myfile = open(file)
x = myfile.readlines()
print (x)当我输入.txt文件时,下面显示了完整的错误消息:
line 10, in <module> x = myfile.readlines()
line 26, in decode return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 318: ordinal not in range(128)发布于 2017-04-27 00:05:04
我没有使用编解码器,而是这样解决它:
def test():
path = './test.log'
file = open(path, 'r+', encoding='utf-8')
while True:
lines = file.readlines()
if not lines:
break
for line in lines:
print(line)你必须准确地给出编码参数。
发布于 2020-04-25 08:22:50
您还可以尝试编码:
with open(file) as f:
for line in f:
line = line.encode('ascii','ignore').decode('UTF-8','ignore')
print(line)发布于 2017-01-15 15:51:04
@AndriiAbramamov是对的,你应该检查这个问题,这是一种方法,你可以打开你的文件,也在该链接上
import codecs
f = codecs.open('words.txt', 'r', 'UTF-8')
for line in f:
print(line)另一种方法是使用正则表达式,这样当您打开文件时,您可以删除任何特殊字符,如双引号等。
https://stackoverflow.com/questions/41512427
复制相似问题