简体   繁体   中英

Changing a list of integers to a string for a file

I have a list of integers which i needed to be sorted and appear on screen (i got that down) but i also need it to be written into a new file.

 data = []
with open('integers.txt','r') as myfile:
   for line in myfile:
        data.extend(map(int, line.split(',')))
print (sorted (data))

text_file = open('sorted_integers.txt', 'w')
text_file.write(sorted(data))
text_file.close()

Do you want to save your output the same way your input was saved? In that case, you can painlessly use print with the file argument.

with open('sorted_integers.txt', 'w') as f:
    print(*sorted(data), sep=',', end='', file=f)

It is always recommended you use the with...as context manager when working with file I/O, it simplifies your code.

If you're working with python2.x, do a __future__ import first:

from __future__ import print_function 

Another point (thanks, PM 2Ring) is that calling list.sort is actually more performant/efficient than sorted , since the original list is sorted in place , instead of returning a new list object, as sorted would do.

In summary,

data.sort() # do not assign the result!

with open('sorted_integers.txt', 'w') as f:
    print(*data, sep=',', end='', file=f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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