[英]Changing a list of integers to a string for a 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()
是否要以保存输入的方式保存输出? 在这种情况下,您可以轻松地将print
与file
参数一起使用。
with open('sorted_integers.txt', 'w') as f:
print(*sorted(data), sep=',', end='', file=f)
始终建议您在处理文件I / O时使用with...as
上下文管理器,这样可以简化代码。
如果您使用的是python2.x, __future__
执行__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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.