1

以下代码所做的只是:它读取文件中的列表,按第二列对其进行排序并将输出写入新文件。

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)

避免写入输出文件的最佳方法是什么,而不是将其存储在内部列表中?

4

1 回答 1

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
于 2013-03-31T23:28:33.550 回答