1

All the following code does is: it reads a list in a file, sorts it out by the second column and writes the output in a new file.

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)

What's the best way to avoid writing the outputfile, so instead storing it in a internal list?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
F4R
  • 403
  • 1
  • 3
  • 11

1 Answers1

1

You can simply reassign to data (with a slice), like this:

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
Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
  • THANKS! It already helped me A LOT! What if I don't want to print this table at all? Is there a way to "store" this in some sort of "internal memory/file" (instead of writing a file) and open wherever I need it in the code? Thanks again, I'm already using those slices in all the code :) good stuff! – F4R Apr 01 '13 at 02:53
  • If you want to use the data during the runtime of the program, you can simply assign it to a variable, which will make the data persist in (virtual) memory until your program is closed. This is how (imperative) programming works, after all. You may be interested in the [Python Tutorial](http://docs.python.org/3/tutorial/introduction.html), which explains these things nicely. – phihag Apr 01 '13 at 11:56