以下所有代码都是:它读取文件中的列表,将其排序到第二列并将输出写入新文件。
import operator
original_flightevent = 'flightevent.out.1'
new_sorted_flightevent = 'flightevent.sorted.out.1'
readfile1 = open(original_flightevent, 'r')
writefile1 = open(new_sorted_flightevent, 'a')
writefile2 = open('flightevent.sorted.out.2', 'a')
def sort_table(table, col=1):
return sorted(table, key=operator.itemgetter(col), reverse=False)
if __name__ == '__main__':
data = (line.strip().split(';') for line in readfile1)
for line in sort_table(data, 1):
print >> writefile1, line
readfile2 = open(new_sorted_flightevent, 'r')
numline=1
for i in range(numline):
readfile2.next()
for line in readfile2:
p=line
if p:
writefile2.write(p)
避免编写输出文件的最佳方法是什么,所以将其存储在内部列表中?
答案 0 :(得分:1)
您可以简单地重新分配数据(使用slice),如下所示:
if __name__ == '__main__':
with open('flightevent.out.1', 'r') as original:
data = (line.strip().split(';') for line in original)
output_data = sort_table(data, 1)[1:]
open('flightevent.sorted.out.1', 'a') as out:
for line in output_data:
print >> out, line