Sort lines in a plain text file alphanumerically

Devyn Collier Johnson devyncjohnson at gmail.com
Tue Aug 6 06:38:08 EDT 2013


On 08/05/2013 11:12 PM, Joshua Landau wrote:
> On 6 August 2013 03:00, Devyn Collier Johnson <devyncjohnson at gmail.com 
> <mailto:devyncjohnson at gmail.com>> wrote:
>
>     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.
>
>
> HINT #1: Don't assume that without a reason. It's wrong.
>
>     >>> file = open('/home/collier/pytest/sort.TXT', 'r').read()
>
>
> HINT #2: Don't lie. "file" is not a file so you probably shouldn't 
> call it one. It's the contents of a file object.
>
>     >>> 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'
>
>
> HINT #3: *Read*. What does it say?
>
>     AttributeError: 'str' object has no attribute 'sort'
>
> Probably your problem, then, is that a 'str' object has no attribute 
> 'sort'. That's what it says.
>
> "file" is a "'str' object". You are accessing the 'sort' attribute 
> which it doesn't have.
>
>     I had the parameters (key=str.casefold, reverse=True), but I took
>     those out to make sure the error was not with my parameters.
>
>
> HINT #4: Don't just guess what the problem is. The answer is in the error.
>
>     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'
>
>
>
>
> So you want to sort your string by lines. Rather than trying to abuse 
> a .sort attribute that patently doesn't exist, just use sorted OR 
> convert to a list first.
>
>     sorted(open('/home/collier/pytest/sort.TXT'), key=str.casefold, 
> reverse=True)
>
> Because it's bad to open files without a with unless you know what 
> you're doing, use a with:
>
>     with open('/home/collier/pytest/sort.TXT') as file:
>         sorted(file, key=str.casefold, reverse=True)

Thanks for the advice Joshua. I find these tips very useful. However, 
how would I close the files, or would they close after the "with" 
construct is complete?

Mahalo,

DCJ
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130806/455198d3/attachment.html>


More information about the Python-list mailing list