将一个整数列表更改为一个文件的字符串
我有一个整数列表,我需要排序并出现在屏幕上(我明白了)但我也需要将它写入一个新文件。将一个整数列表更改为一个文件的字符串
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()
回答:
您是否希望以与保存输入相同的方式保存输出?在这种情况下,您可以轻松使用print
和file
参数。
with open('sorted_integers.txt', 'w') as f: print(*sorted(data), sep=',', end='', file=f)
这是总是推荐您使用with...as
上下文管理使用File I/O,它简化了你的代码的时候。
如果你使用python2.x工作,首先做一个__future__
进口:
from __future__ import print_function
另一点(感谢,PM 2Ring)是调用list.sort
实际上是更好的性能/效率比sorted
,因为原始列表排序到位,而不是返回一个新的列表对象,因为sorted
会做。
综上所述,
data.sort() # do not assign the result! with open('sorted_integers.txt', 'w') as f:
print(*data, sep=',', end='', file=f)
以上是 将一个整数列表更改为一个文件的字符串 的全部内容, 来源链接: utcz.com/qa/257214.html