Need help on reading line from file into list

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Apr 3 17:53:27 EDT 2007


bahoo a écrit :
> On Apr 3, 5:06 pm, Bruno Desthuilliers
> <bdesth.quelquech... at free.quelquepart.fr> wrote:
> 
(snip)
>> >>> open('source.txt').readlines()
>>['0024\n']
>> >>> map(str.strip, open('source.txt').readlines())
>>['0024']
>> >>> open('source.txt').read()
>>'0024\n'
>> >>> list(open('source.txt').read().strip())
>>['0', '0', '2', '4']
>> >>>
> 
> 
> Thanks, this helped a lot.
> I am now using the suggested
> map(str.strip, open('source.txt').readlines())

Note that for production code, you should do it the long way (ie: 
explicitely opening and handling exceptions to make sure you're closing 
it).

> However, I am a C programmer,

Welcome onboard then.

> and I have a bit difficulty
> understanding the syntax.
 >
> I don't see where the "str" came from,

It's the builtin string type. strip() is a method of string objects, and 
in Python, instance.method() is equivalent to Class.method(instance).


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

Nope. The result of file.readlines() is a list of strings.

The builtin function map(callable, sequence) return the result of 
applying function 'callable' to each element of the sequence - the 
imperative equivalent would be:

f = open('source.txt')
result = []
for line in f.readlines():
   # line is a str instance, so we call strip() directly on it
   result.append(line.strip())
f.close()

There's also the 'list comprehension' syntax, which you'll see quite 
frequently:

result = [line.strip() for line in f.readlines()]

HTH



More information about the Python-list mailing list