[Newbie]Trouble with string method

calpolynate nathanjohns77 at hotmail.com
Fri Mar 26 13:21:25 EST 2004


"Robert Brewer" <fumanchu at amor.org> wrote in message news:<mailman.431.1080255513.742.python-list at python.org>...
> 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

Yes Robert,

That's what I was looking for. Sean's worked too, but it sorted
without changing uppercase to lowercase, I should have been more
detailed in what I was trying to do.

How should I go about creating an exception for changing from upper to
lower? I.E., if the latter part of a line has a comment (#XYZ) and I
would like to keep those uppercase, what would be a good way to
implement that in with the existing code?

Thanks,

Nathan



More information about the Python-list mailing list