[英]Encoding issue when writing to text file, with Python
我正在编写一个程序,使用简短的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”作为编码的一种解释: Unicode和UTF-8有什么区别?
TLDR: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)
您需要告诉Python使用Unicode字符编码来解码希伯来字符。 这是如何在Python中读取Unicode字符的链接: 从Python文件中读取字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.