Reputation: 5068
In unix (specifically, I'm using bash
), I can sort the contents of a file easily; given I have a file:
chris@chris:~$ cat testSort.txt
3 1 test01
8 2 test02
6 3 test03
7 4 test04
1 5 test05
Running sort
will return the sorted values based on the 1st column
chris@chris:~$ sort testSort.txt
1 5 test05
3 1 test01
6 3 test03
7 4 test04
8 2 test02
the results of which I can pipe into a file or a program as necessary; is there a way as easy as this in python, or do I need to read my file in, save it as a data structure of some sort, and then save it again?
Confusion
I'm not sure why I've received a downvote - I asked if there was a way as simple as in unix (i.e. a 1 word command) to achieve a sort. I even provided an example to show what I wanted? In what way does this mean that "the question shows no research effort, it is unclear or not useful"?
Upvotes: 1
Views: 6164
Reputation: 309949
How easily do you want to do it? This sorts lexicographically, but you can modify it to sort based on any arbitrary criterion you have by passing an additional key
function to sorted
.
with open('input') as f:
sorted_file = sorted(f)
#save to a file
with open('output') as f:
f.writelines(sorted_file)
#write to stdout
import sys
sys.stdout.writelines(sorted_file)
Upvotes: 4