Need help on reading line from file into list
bdesth.quelquechose at free.quelquepart.fr
Tue Apr 3 23:53:27 CEST 2007
bahoo a écrit :
> On Apr 3, 5:06 pm, Bruno Desthuilliers
> <bdesth.quelquech... at free.quelquepart.fr> wrote:
>> >>> open('source.txt').readlines()
>> >>> map(str.strip, open('source.txt').readlines())
>> >>> open('source.txt').read()
>> >>> 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
> 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
There's also the 'list comprehension' syntax, which you'll see quite
result = [line.strip() for line in f.readlines()]
More information about the Python-list