Need help on reading line from file into list

B

bahoo

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 )
 
B

bahoo

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

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!
 
B

Bruno Desthuilliers

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

Grant Edwards

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.['__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.
 
B

Bruno Desthuilliers

bahoo a écrit :
On Apr 3, 5:06 pm, Bruno Desthuilliers
(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
 
M

Mel Wilson

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

Duncan Booth

bahoo said:
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).
 
B

bearophileHUGS

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

Probably better, lazily:
result = [line.strip() for line in infile]

Bye,
bearophile
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
Bruno Desthuilliers:
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...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top