sorting content of a text file in python
Posted
by rabidmachine9
on Stack Overflow
See other posts from Stack Overflow
or by rabidmachine9
Published on 2010-06-09T00:41:21Z
Indexed on
2010/06/09
0:52 UTC
Read the original article
Hit count: 283
python
I have this small script that sorts the content of a text file
# The built-in function `open` opens a file and returns a file object.
# Read mode opens a file for reading only.
try:
f = open("tracks.txt", "r")
try:
# Read the entire contents of a file at once.
# string = f.read()
# OR read one line at a time.
#line = f.readline()
# OR read all the lines into a list.
lines = f.readlines()
lines.sort()
f = open('tracks.txt', 'w')
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()
except IOError:
pass
the only problem is that the text is displayed at the bottom of the text file everytime it's sortened...
I assume it also sorts the blank lines...anybody knows why? thanks in advance
© Stack Overflow or respective owner