python - Processing files in memory -


i have file each line like

name1 name2 name3

i can read in line line, split each line, process line , output processed line line.

however read whole file in, sort middle column, output whole sorted file in same format input in.

my first attempt splits each line read in make list of tuples, sorts using key= , rejoins each tuple , outputs line line.

is there more pythonic way of doing this?

something ought do:

with open('datafile') fin:     lines = list(fin)     lines.sort(key=lambda line: line.split()[1])  open('outfile','w') fout:     fout.writelines(lines) 

a few notes:

  • my sort key bit ugly. however, advantage here preserves lines in input file. if split lines , sorted, code might little prettier, need join split lines correctly on output (plus, runs of whitespace might lost)

  • outfile can same filename datafile make change "in place"

  • if need support quoting of fields (field1 "field 2" field3), you'll want @ csv module.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -