这里还有一些关于这个问题的其他问题,但到目前为止还没有解决我的问题.
我有一个很大的(40MB)CSV文件.文件的大部分以iso-8859-1(Latin1)编码,但一些条目(仅条目!)采用的是utf-8格式.
如果我试图打开使用utf-8编码的文件,python已经抛出了一个编码错误.如果我打开iso-8859-1中的文件,该文件是可以读取的,但是一些条目仍然是mojibake.
我try 了以下代码来在线修复问题,但显然我遗漏了一些东西,因为utf-8条目仍然是mojibake.
import os
import ftfy
# There are issues with file encoding with this file. Try to convert it to proper utf-8
sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
sourceFileName = os.path.join(folder, file + config.CSV_EXTENSION)
targetFileName = os.path.join(folder, file + "_temp" + config.CSV_EXTENSION)
# input file
csvfile = open(sourceFileName, "r", encoding = sourceEncoding)
Lines = csvfile.readlines()
for line in Lines:
line = ftfy.fix_encoding(line)
# output stream
outfile = open(targetFileName, "w", encoding = targetEncoding) # Windows doesn't like utf8
outfile.writelines(Lines)
# close files
csvfile.close()
outfile.close()
os.remove(sourceFileName)
os.rename(targetFileName, sourceFileName)
我拥有的一个特定字符串如下所示:
Ãberarbeitung A6 Heft
个
我希望它看起来是这样的:
Überarbeitung A6 Heft
个
编辑:
一些澄清.
我假设文件中有一些编码问题,因为我知道CSV中的条目有两个不同的来源.大多数查询是通过在图形用户界面中键入值来实现的.一些值来自自己编写的脚本,天知道是什么编码.
如果我在VSCode中打开CSV,它会假定它是ISO-8859-1.但有些条目看起来像我上面提到的:
Ãberarbeitung A6 Heft
如果我将编码更改为UTF-8,则此条目变为‘Right’:
Überarbeitung A6 Heft
但随后其他条目变得更糟:
Testdurchf�hrung
try 打开使用UTF-8编码的文件时,错误消息为:
Exception has occurred: UnicodeDecodeError
'utf-8' codec can't decode byte 0xe4 in position 56: invalid continuation byte
我将try 导入CSV二进制文件并对其进行线状解码.也许这能奏效.