使用python将Ansi转换为UTF-8导致错误



当我试图编写一个将Ansi转换为UTF-8的python程序时,我发现了这个

https://stackoverflow.com/questions/14732996/how-can-i-convert-utf-8-to-ansi-in-python

将UTF-8转换为Ansi。

我想只要颠倒顺序就可以了。所以我写了

file_path_ansi = "input.txt"
file_path_utf8 = "output.txt"
#open and encode the original content
file_source = open(file_path_ansi, mode='r', encoding='latin-1', errors='ignore')
file_content = file_source.read()
file_source.close
#write 
file_target = open(file_path_utf8, mode='w', encoding='utf-8')
file_target.write(file_content)
file_target.close

但是会导致错误。

TypeError: file<> takes at most 3 arguments <4 given>

所以我改变了

file_source = open(file_path_ansi, mode='r', encoding='latin-1', errors='ignore')

file_source = open(file_path_ansi, mode='r', encoding='latin-1')

然后导致另一个错误:

TypeError: 'encoding' is an invalid keyword arguemtn for this function

我应该如何修复我的代码来解决这个问题?

您正在尝试在Python 2上使用Python 3版本的open()函数。在主要版本之间,对I/O的支持进行了彻底的改进,支持更好的编码和解码。

您可以在Python 2中获得与io.open()相同的新版本。

我将使用shutil.copyfileobj()函数进行复制,因此您不必将整个文件读取到内存中:

import io
import shutil
with io.open(file_path_ansi, encoding='latin-1', errors='ignore') as source:
    with io.open(file_path_utf8, mode='w', encoding='utf-8') as target:
        shutil.copyfileobj(source, target)

不过要小心;大多数谈论ANSI的人指的是Windows代码页中的一个;您可能真的在CP (codepage) 1252中有一个文件,它几乎是,但与ISO-8859-1(拉丁1)不完全相同。如果是这样,使用cp1252代替latin-1作为encoding参数。

最新更新