On 6 August 2013 03:00, Devyn Collier Johnson <devyncjohn...@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)
-- http://mail.python.org/mailman/listinfo/python-list