Need help on reading line from file into list

Grant Edwards grante at visi.com
Tue Apr 3 17:19:34 EDT 2007


On 2007-04-03, bahoo <b83503104 at yahoo.com> wrote:


> Thanks, this helped a lot.
> I am now using the suggested
> map(str.strip, open('source.txt').readlines())
>
> However, I am a C programmer, and I have a bit difficulty
> understanding the syntax.

That bit of syntax is completely, utterly, 100%, identical to
C:

 1) open('source.txt') is called which returns a file object
    (think of it sort of like a struct).

 2) the readlines() method of that file object is then called.

 3) str.strip and the return value from readlines() are then
    passed as parameters to the map() function. 

> I don't see where the "str" came from,

You really ought to go through one or more of the tutorials.
"str" is a built-in type:

$ python
Python 2.4.3 (#1, Dec 10 2006, 22:09:09) 
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> print str
<type 'str'>

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__',
'__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__getslice__', '__gt__',
'__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__str__', 'capitalize', 'center', 'count',
'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']

> so perhaps the output of "open('source.txt').readlines()" is
> defaulted to "str?

Sorry, I don't know that that means.

The return value from open('sources.txt').readlines() is being
passed as the second parameter to the map() function.
str.strip is being passed as the first parameter to map.

-- 
Grant Edwards                   grante             Yow!  Is there something
                                  at               I should be DOING with a
                               visi.com            GLAZED DONUT??



More information about the Python-list mailing list