Sort lines in a plain text file alphanumerically
Devyn Collier Johnson
devyncjohnson at gmail.com
Mon Aug 5 22:00:55 EDT 2013
I am wanting to sort a plain text file alphanumerically by the lines. I
have tried this code, but I get an error. I assume this command does not
accept newline characters.
>>> file = open('/home/collier/pytest/sort.TXT', 'r').read()
>>> print(file)
z
c
w
r
h
s
d
>>> file.sort() #The first blank line above is from the file. I do not
know where the second comes from.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'sort'
I had the parameters (key=str.casefold, reverse=True), but I took those
out to make sure the error was not with my parameters.
Specifically, I need something that will sort the lines. They may
contain one word or one sentence with punctuation. I need to reverse the
sorting ('z' before 'a'). The case does not matter ('a' = 'A').
I have also tried this without success:
>>> file.sort(key=str.casefold, reverse=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'sort'
Mahalo,
DevynCJohnson at Gmail.com
More information about the Python-list
mailing list