Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52023 > unrolled thread

Re: Sort lines in a plain text file alphanumerically

Started byDevyn Collier Johnson <devyncjohnson@gmail.com>
First post2013-08-06 06:35 -0400
Last post2013-08-06 06:35 -0400
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Sort lines in a plain text file alphanumerically Devyn Collier Johnson <devyncjohnson@gmail.com> - 2013-08-06 06:35 -0400

#52023 — Re: Sort lines in a plain text file alphanumerically

FromDevyn Collier Johnson <devyncjohnson@gmail.com>
Date2013-08-06 06:35 -0400
SubjectRe: Sort lines in a plain text file alphanumerically
Message-ID<mailman.238.1375785358.1251.python-list@python.org>
On 08/05/2013 10:19 PM, MRAB wrote:
> On 06/08/2013 03:00, Devyn Collier Johnson 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.
>>
>>
>>   >>> file = open('/home/collier/pytest/sort.TXT', 'r').read()
>
> That returns the file as a single string.
>
>>   >>> 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'
>>
> Strings don't have a sort method.
>
>> 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'
>>
> Try this:
>
> lines = open('/home/collier/pytest/sort.TXT', 'r').readlines()
> lines.sort()
>
>
> Actually, a more Pythonic way these days is to use the 'with' statement:
>
> with open('/home/collier/pytest/sort.TXT') as file:
>     lines = file.readlines()
>
> lines.sort()
>

Thanks! That works well. After I run your command, I run

print(''.join(lines))

to get the sorted output. Even the parameters work without issues.

lines.sort(reverse=True, key=str.casefold)


Mahalo,

DCJ

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web