473,414 Members | 1,703 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

Need help on reading line from file into list

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 )

Apr 3 '07 #1
8 1983
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']
>>>
Apr 3 '07 #2
On Apr 3, 5:06 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
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']
>>>
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!

Apr 3 '07 #3
bahoo a écrit :
On Apr 3, 5:06 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
(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
Apr 3 '07 #4
On 2007-04-03, bahoo <b8*******@yahoo.comwrote:

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.
>>print str
<type 'str'>
>>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']
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??
Apr 3 '07 #5
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.
Apr 4 '07 #6
"bahoo" <b8*******@yahoo.comwrote:
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).
Apr 4 '07 #7
Bruno Desthuilliers:
result = [line.strip() for line in f.readlines()]
Probably better, lazily:
result = [line.strip() for line in infile]

Bye,
bearophile

Apr 4 '07 #8
be************@lycos.com 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...

Apr 4 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: JackM | last post by:
Let me attempt to explain my problem. I have a crude php script that takes a text list of songs that was generated by an mp3 list program and translates each entry into the form where they can be...
7
by: Scott Brady Drummonds | last post by:
Hi, everyone, I'm a Python novice and would love some tips on how I should perform the following task: I'd like to have my Python script read objects (using their constructors) and terminate...
45
by: Joh | last post by:
hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = would like to produce : , , , ,
4
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be
7
by: RFQ | last post by:
Hi, I'm struggling here to do the following with any success: I have a comma delimited file where each line in the file is something like: PNumber,3056,Contractor,XYZ Contracting,Architect,ABC...
2
by: Keith Kowalski | last post by:
I anm opening up a text file reading the lines of the file that refer to a tif image in that file, If the tif image does not exist I need it to send an email stating that the file doesn't exist...
16
by: didier.doussaud | last post by:
I have a stange side effect in my project : in my project I need to write "gobal" to use global symbol : .... import math .... def f() : global math # necessary ?????? else next line...
8
by: skumar434 | last post by:
i need to store the data from a data base in to structure .............the problem is like this ....suppose there is a data base which stores the sequence no and item type etc ...but i need only...
0
by: Anish G | last post by:
Hi, I have an issue with reading CSV files. I am to reading CSV file and putting it in a Datatable in C#. I am using a regular expression to read the values. Below is the code. Now, it reads...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.