Problem 2.5
Sort a file
Write a program sort.py
that takes filename as a command-line argument and prints lines in that file in the sorted order.
There are two sample files files/names.txt
and files/blake.txt
to try your program against.
$ cat files/names.txt
bob
dave
charlie
alice
$ python sort.py files/names.txt
alice
bob
charlie
dave
$ cat files/blake.txt
Piping down the valleys wild
Piping songs of pleasant glee
On a cloud I saw a child.
And he laughing said to me.
Pipe a song about a Lamb;
So I piped with merry chear,
Piper pipe that song again—
So I piped, he wept to hear.
$ python sort.py files/blake.txt
And he laughing said to me.
On a cloud I saw a child.
Pipe a song about a Lamb;
Piper pipe that song again—
Piping down the valleys wild
Piping songs of pleasant glee
So I piped with merry chear,
So I piped, he wept to hear.
Solution
import sys
path = sys.argv[1]
lines = open(path).readlines()
for line in sorted(lines):
print(line, end="")