将文本文件的编码从utf-8转换为ansi或python中的unicode

Convert encoding of a text file from utf-8 to ansi or unicode in python

我有一个UTF-8编码的文本文件。我想在python中将它的unicode自动更改为ansi或unicode。有可能吗?我该怎么做?


试试这个

1
2
3
4
5
6
7
#read input file
with codecs.open('USERS.CSV', 'r', encoding = 'latin-1') as file:
lines = file.read()  

#write output file
with codecs.open('1_UserPython.CSV', 'w', encoding = 'utf_8_sig') as file:
file.write(lines)

要将文件从utf8转换为cp1252,请执行以下操作:

1
2
3
4
5
6
import io

with io.open(src_path, mode="r", encoding="utf8") as fd:
    content = fd.read()
with io.open(dst_path, mode="w", encoding="cp1252") as fd:
    fd.write(content)