Need help on reading line from file into list

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


bahoo a écrit :
> 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'] ?

> 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.



> 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 :

> 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.

 >>> 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']
 >>>



More information about the Python-list mailing list