[Newbie]Trouble with string method

Robert Brewer fumanchu at amor.org
Thu Mar 25 23:56:38 CET 2004


Sean Berry wrote:
> Try the following
> 
> unsorted = open('unsorted', 'r').readlines() -- two steps into one
> unsorted.sort(lambda x, y: cmp(string.lower(x), string.lower(y)))
> unsorted.close()
> sorted = open('sorted', 'w')
> sorted.writelines(unsorted)
> soretd.close()
> 
> Your problem is that you are trying to use a string method on a list.
> 
> 
> calpolynate <nathanjohns77 at hotmail.com> wrote in message
> news:96fd272b.0403251442.49047ba9 at posting.google.com...
> > I'm attempting to open a file, read the lines, sort them, change any
> > uppercase character to lowercase, and output to another file:
> >
> > import string
> >
> > unsorted = open('unsorted', 'r')
> > L = unsorted.readlines()
> > L.sort()
> > L = L.lower()
> > sorted = open('sorted', 'w')
> > sorted.writelines(L)
> > unsorted.close()
> > sorted.close()
> >
> > when trying to run, I get this traceback:
> >
> > Traceback (most recent call last):
> >   File "sort_list.py", line 6, in ?
> >     L = L.lower(L)
> > AttributeError: 'list' object has no attribute 'lower'
> >
> > Do I need to somehow convert the list into strings?
> >
> > Thanks for any help!

I think he wanted the output to be lowercase, not just sorted
case-insensitively (that's how I read it anyway). Try:

lines = [line.lower() for line in open('unsorted', 'r')]
lines.sort()
sorted = open('sorted', 'w')
sorted.writelines(lines)
sorted.close()


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list