473,888 Members | 1,554 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.t xt','r')
for line in infile:
line.join(line)
my_list.extend( line )

Apr 3 '07 #1
8 2006
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.t xt','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.tx t').readlines() )
['0024']
>>open('source. txt').read()
'0024\n'
>>list(open('so urce.txt').read ().strip())
['0', '0', '2', '4']
>>>
Apr 3 '07 #2
On Apr 3, 5:06 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.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.t xt','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.tx t').readlines() )
['0024']
>>open('source. txt').read()
'0024\n'
>>list(open('so urce.txt').read ().strip())
['0', '0', '2', '4']
>>>
Thanks, this helped a lot.
I am now using the suggested
map(str.strip, open('source.tx t').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.t xt').readlines( )" is defaulted to "str?

Thanks!

Apr 3 '07 #3
bahoo a écrit :
On Apr 3, 5:06 pm, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :
(snip)
>>open('source. txt').readlines ()
['0024\n']
>>map(str.strip , open('source.tx t').readlines() )
['0024']
>>open('source. txt').read()
'0024\n'
>>list(open('so urce.txt').read ().strip())
['0', '0', '2', '4']
>>>


Thanks, this helped a lot.
I am now using the suggested
map(str.strip, open('source.tx t').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(in stance).

so perhaps the output of
"open('source.t xt').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.tx t')
result = []
for line in f.readlines():
# line is a str instance, so we call strip() directly on it
result.append(l ine.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*******@yaho o.comwrote:

Thanks, this helped a lot.
I am now using the suggested
map(str.strip, open('source.tx t').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.tx t') 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.t xt').readlines( )" is
defaulted to "str?
Sorry, I don't know that that means.

The return value from open('sources.t xt').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.tx t').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.t xt').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*******@yaho o.comwrote:
I don't see where the "str" came from, so perhaps the output of
"open('source.t xt').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
2022
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 inserted into my mySQL database in the proper fields although it is currently being written to another text file because of the problem I have below. The lines from the mp3 text file will look like this: Al Green - The Supreme Al Green - 01 -...
7
10850
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 gracefully when an EOF is encountered. My first attempt looked like this: # This is enclosed in a 'try' block file = open(...) while 1:
45
3064
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
3072
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
7667
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 Architects,... So each line is intended to be: key1,value1,key2,value2,key3,value3... and each line is to be variable in length (although it will have to be an even number of records so that each key has a value).
2
4453
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 then skip this file and move onto the next file (line). If file is there then move to a sirectory. Here is the code I have (Feel free to make corrections as needed. If possible make changes in red)
16
3129
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 generate an error message ?????
8
2759
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 the sequence nos and it should be such that i can access it through the structure .plz help me .
0
2201
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 CSV file without any issues only if all the fields are not null. If any field is blank, it moves the values to the left and displays the value under invalid column. Example is shown below: A part of CSV file. I am reading the first row as...
0
9961
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9800
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11182
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10778
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10439
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9597
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7990
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7148
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4642
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.