Skip to main content
 首页 » 编程设计

python之使用 Python 写入文本文件时出现编码问题

2025年05月04日7JeffreyZhao

我正在编写一个程序,使用简短的 Python 脚本“手动”将 csv 文件安排为正确的 JSON 语法。在输入文件中,我使用 readlines() 将文件格式化为行列表,我对其进行操作并将其合并为一个字符串,然后将其输出到一个单独的 .txt 文件中。然而,输出包含乱码而不是输入文件中存在的希伯来字符,并且输出是双倍行距的,水平的(每个字符之间添加了一个空白字符)。据我所知,问题与编码有关,但我一直无法弄清楚是什么。当我检测输入和输出文件的编码时(使用 .encoding 属性),它们都返回 None,这意味着它们使用系统默认值。技术细节:Python 2.7、Windows 7。

虽然关于这个主题有很多问题,但我没有找到我的问题的直接答案。 在这种情况下,检测系统默认值对我没有帮助,因为我需要程序是可移植的。

代码如下:

def txt_to_JSON(csv_list): 
    ...some manipulation of the list... 
    return JSON_string 
file_name = "input_file.txt" 
my_file = open(file_name) 
# make each line of input file a value in a list 
lines = my_file.readlines() 
# break up each line into a list such that each 'column' is a value in that list  
for i in range(0,len(lines)): 
    lines[i] = lines[i].split("\t") 
J_string = txt_to_JSON(lines) 
json_file = open("output_file.txt", "w+") 
json_file.write(jstring) 
json_file.close() 

请您参考如下方法:

所有数据都需要编码才能存储在磁盘上。如果你不知道编码,你能做的最好的就是猜测。有一个图书馆:https://pypi.python.org/pypi/chardet

我强烈推荐 Ned Batchelder 的演讲 http://nedbatchelder.com/text/unipain.html 了解详情。

关于在 Windows 上使用“unicode”作为编码的解释:What's the difference between Unicode and UTF-8?

长篇大论: Microsoft 使用 UTF16 作为 unicode 字符串的编码,但决定将其称为“unicode”,因为他们也在内部使用它。

即使 Python2 在字符串/unicode 转换方面有点宽松,您也应该习惯于始终在输入时解码并在输出时编码。

你的情况

filename = 'where your data lives' 
with open(filename, 'rb') as f: 
   encoded_data = f.read() 
decoded_data = encoded_data.decode("UTF16") 
 
# do stuff, resulting in result (all on unicode strings) 
result = text_to_json(decoded_data) 
 
encoded_result = result.encode("UTF-16")  #really, just using UTF8 for everything makes things a lot easier 
outfile = 'where your data goes' 
with open(outfile, 'wb') as f: 
    f.write(encoded_result)