简体   繁体   English

将列表写入文件txt(utf-8)

[英]Write list to file txt(utf-8)

I tried to write a list to txt file with the encoding utf-8 without BOM. 我试图用utf-8编码将清单写入txt文件,而没有BOM。 But have a problem is: If i create that file with utf-8 withou BOM encoding: 但是有一个问题是:如果我使用带有BOM表编码的utf-8创建该文件:

  ポ
  1
  田
  11
  直
  11
  子
  11

and use my function to read it to a list: 并使用我的函数将其读取到列表中:

import codecs
def file_to_list(file_name):
    results = []
    f = codecs.open(file_name, encoding='utf-8')
    for line in f:
        results.append(line.replace('\r\n', ''))
    return results
list_1 = file_to_list('test_read.txt')
print(list_1)

I got the ok result : ['ポ', '1', '田', '11', '直', '11', '子', '11'] But after this i using another function to write back to file and read that file again, a problem appear: 我得到了好的结果: ['ポ', '1', '田', '11', '直', '11', '子', '11']但是在此之后,我使用了另一个函数写回文件并再次读取该文件,出现问题:

def list_to_file(file_name, thelist):
    f = codecs.open(file_name, "w", encoding='utf-8')
    for item in thelist:
        f.write("%s\n" % item)
list_to_file('test_read.txt', list_1)
list_2 = file_to_list('test_read.txt')
print(list_2)

the return of print is : ['ポ\\n', '1\\n', '田\\n', '11\\n', '直\\n', '11\\n', '子\\n', '11\\n'] So, what wrong to make '\\n' ? 打印的返回值是: ['ポ\\n', '1\\n', '田\\n', '11\\n', '直\\n', '11\\n', '子\\n', '11\\n']那么,使'\\n'什么错呢?

You should not be replacing trailing whitespaces/new line characters as they may vary across platforms. 您不应该替换尾随空格/换行符,因为它们可能因平台而异。 You should strip them. 你应该剥掉它们。 More so, you're writing to the file with only \\n , but your function expects \\r\\n . 更重要的是,您仅使用\\n写入文件,但是您的函数期望使用\\r\\n

In your file_to_list function, replace: 在您的file_to_list函数中,替换为:

results.append(line.replace('\r\n', ''))

with

results.append(line.rstrip())

See: 看到:

>>> 'some line\n'.replace('\r\n', '')
'some line\n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM