AlphaWolf AlphaWolf - 1 year ago 97
Python Question

Write list to file txt(utf-8)

I tried to write a list to txt file with the encoding utf-8 without BOM. But have a problem is:
If i create that file with utf-8 withou BOM encoding:





and use my function to read it to a list:

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

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:

def list_to_file(file_name, thelist):
f =, "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')

the return of print is :
['ポ\n', '1\n', '田\n', '11\n', '直\n', '11\n', '子\n', '11\n']

So, what wrong to make

Answer Source

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.

In your file_to_list function, replace:

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




>>> 'some line\n'.replace('\r\n', '')
'some line\n'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download