Connecting Tech Pros Worldwide Forums | Help | Site Map

Need help on reading line from file into list

bahoo
Guest
 
Posts: n/a
#1: Apr 3 '07
Hi,

I have a text file containing a single line of text, such as
0024

How should I read it into a "list"?

I tried this, but the "join" did not work as expected. Any
suggestions?

infile = open('my_file.txt','r')
for line in infile:
line.join(line)
my_list.extend( line )


Bruno Desthuilliers
Guest
 
Posts: n/a
#2: Apr 3 '07

re: Need help on reading line from file into list


bahoo a écrit :
Quote:
Hi,
>
I have a text file containing a single line of text, such as
0024
>
How should I read it into a "list"?
You mean ['0024'], or ['0', '0', '2', '4'] ?
Quote:
I tried this, but the "join" did not work as expected.
What did you expect ?

help(str.join)
join(...)
S.join(sequence) -string

Return a string which is the concatenation of the strings in the
sequence. The separator between elements is S.


Quote:
Any
suggestions?
Honestly, the first would be to learn to ask questions, and the second
to pay more attention to what's written in the doc. But let's try :
Quote:
infile = open('my_file.txt','r')
for line in infile:
line.join(line)
my_list.extend( line )
>
If you have a single line of text, you don't need to iterate.

file has a readlines() method that will return a list of all lines. It
also has a read() method that reads the whole content. Notice that none
of these methods will strip newlines characters.

Also, str has a strip() method that - by default - strip out any
'whitespace' characters - which includes newline characters. And
finally, passing a string as an argument to list's constructor gives you
a list of the characters in the string.

This is all you need to know to solve your problem - or at least the two
possible definitions of it I mentionned above.
Quote:
Quote:
Quote:
>>open('source.txt').readlines()
['0024\n']
Quote:
Quote:
Quote:
>>map(str.strip, open('source.txt').readlines())
['0024']
Quote:
Quote:
Quote:
>>open('source.txt').read()
'0024\n'
Quote:
Quote:
Quote:
>>list(open('source.txt').read().strip())
['0', '0', '2', '4']
Quote:
Quote:
Quote:
>>>
bahoo
Guest
 
Posts: n/a
#3: Apr 3 '07

re: Need help on reading line from file into list


On Apr 3, 5:06 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
Quote:
bahoo a écrit :
>
Quote:
Hi,
>
Quote:
I have a text file containing a single line of text, such as
0024
>
Quote:
How should I read it into a "list"?
>
You mean ['0024'], or ['0', '0', '2', '4'] ?
>
Quote:
I tried this, but the "join" did not work as expected.
>
What did you expect ?
>
help(str.join)
join(...)
S.join(sequence) -string
>
Return a string which is the concatenation of the strings in the
sequence. The separator between elements is S.
>
Quote:
Any
suggestions?
>
Honestly, the first would be to learn to ask questions, and the second
to pay more attention to what's written in the doc. But let's try :
>
Quote:
infile = open('my_file.txt','r')
for line in infile:
line.join(line)
my_list.extend( line )
>
If you have a single line of text, you don't need to iterate.
>
file has a readlines() method that will return a list of all lines. It
also has a read() method that reads the whole content. Notice that none
of these methods will strip newlines characters.
>
Also, str has a strip() method that - by default - strip out any
'whitespace' characters - which includes newline characters. And
finally, passing a string as an argument to list's constructor gives you
a list of the characters in the string.
>
This is all you need to know to solve your problem - or at least the two
possible definitions of it I mentionned above.
>
Quote:
Quote:
>>open('source.txt').readlines()
['0024\n']
Quote:
Quote:
>>map(str.strip, open('source.txt').readlines())
['0024']
Quote:
Quote:
>>open('source.txt').read()
'0024\n'
Quote:
Quote:
>>list(open('source.txt').read().strip())
['0', '0', '2', '4']
Quote:
Quote:
>>>
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.
I don't see where the "str" came from, so perhaps the output of
"open('source.txt').readlines()" is defaulted to "str?

Thanks!

Bruno Desthuilliers
Guest
 
Posts: n/a
#4: Apr 3 '07

re: Need help on reading line from file into list


bahoo a écrit :
Quote:
On Apr 3, 5:06 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
>
(snip)
Quote:
Quote:
Quote:
>>open('source.txt').readlines()
>>['0024\n']
Quote:
>>map(str.strip, open('source.txt').readlines())
>>['0024']
Quote:
>>open('source.txt').read()
>>'0024\n'
Quote:
>>list(open('source.txt').read().strip())
>>['0', '0', '2', '4']
Quote:
>>>
>
>
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).
Quote:
However, I am a C programmer,
Welcome onboard then.
Quote:
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).

Quote:
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
Grant Edwards
Guest
 
Posts: n/a
#5: Apr 3 '07

re: Need help on reading line from file into list


On 2007-04-03, bahoo <b83503104@yahoo.comwrote:

Quote:
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.
Quote:
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.
Quote:
Quote:
Quote:
>>print str
<type 'str'>
Quote:
Quote:
Quote:
>>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']
Quote:
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??
Mel Wilson
Guest
 
Posts: n/a
#6: Apr 4 '07

re: Need help on reading line from file into list


bahoo wrote:
[ ... ]
Quote:
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.
I don't see where the "str" came from, so perhaps the output of
"open('source.txt').readlines()" is defaulted to "str?
You can do without.

[x.strip() for x in open ('source.txt', 'r')]

will also work.

Cheers, Mel.


Duncan Booth
Guest
 
Posts: n/a
#7: Apr 4 '07

re: Need help on reading line from file into list


"bahoo" <b83503104@yahoo.comwrote:
Quote:
I don't see where the "str" came from, so perhaps the output of
"open('source.txt').readlines()" is defaulted to "str?
Apart from Grant's explanation that str is the type of a string, what you
perhaps haven't yet grasped is that if you have a type and an instance of
that type there is an equivalence between calling a method on the instance,
or calling the method directly on the type and passing the instance as the
first parameter.

i.e. Given a type T and an instance I (so that type(I)==T) the following
two are equivalent:

I.method(args)
T.method(I, args)

what that means in this particular case is that if you have a string
'line' and want to strip leading and trailing whitespace you can call
either:

line.strip()
or:
str.strip(line)

So str.strip is just another way to refer to the strip method of a str (but
you do have to know that the line is a str rather than another type or it
won't work).
bearophileHUGS@lycos.com
Guest
 
Posts: n/a
#8: Apr 4 '07

re: Need help on reading line from file into list


Bruno Desthuilliers:
Quote:
result = [line.strip() for line in f.readlines()]
Probably better, lazily:
result = [line.strip() for line in infile]

Bye,
bearophile

Bruno Desthuilliers
Guest
 
Posts: n/a
#9: Apr 4 '07

re: Need help on reading line from file into list


bearophileHUGS@lycos.com a écrit :
Quote:
Bruno Desthuilliers:
Quote:
>result = [line.strip() for line in f.readlines()]
>
Probably better, lazily:
result = [line.strip() for line in infile]
This is of course better in the general case, but I wanted to stay
consistant with the other examples...

Closed Thread