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

nar*_*ges 4 python encoding text ansi utf-8

我有一个 utf-8 编码的文本文件。我想在python中自动将它的unicode更改为ANSI或unicode。是否可以?我该怎么做?

小智 6

尝试这个

#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)
Run Code Online (Sandbox Code Playgroud)


Lau*_*RTE 4

要将文件从 utf8 转换为 cp1252:

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)
Run Code Online (Sandbox Code Playgroud)