473,656 Members | 2,997 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

altering an object as you iterate over it?

What is the best way of altering something (in my case, a file) while
you are iterating over it? I've tried this before by accident and got an
error, naturally.

I'm trying to read the lines of a file and remove all the blank ones.
One solution I tried is to open the file and use readlines(), then copy
that list into another variable, but this doesn't seem very efficient to
have two variables representing the file.

Perhaps there's also some better to do it than this, including using
readlines(), but I'm most interested in just how you edit something as
you are iterating with it.

Thanks.
May 19 '06 #1
28 1806
John Salerno wrote:
What is the best way of altering something (in my case, a file) while
you are iterating over it? I've tried this before by accident and got an
error, naturally.

I'm trying to read the lines of a file and remove all the blank ones.
One solution I tried is to open the file and use readlines(), then copy
that list into another variable, but this doesn't seem very efficient to
have two variables representing the file.

Perhaps there's also some better to do it than this, including using
readlines(), but I'm most interested in just how you edit something as
you are iterating with it.

Thanks.


Slightly new question as well. here's my code:

phonelist = open('file').re adlines()
new_phonelist = phonelist

for line in phonelist:
if line == '\n':
new_phonelist.r emove(line)

import pprint
pprint.pprint(n ew_phonelist)

But I notice that there are still several lines that print out as '\n',
so why doesn't it work for all lines?
May 19 '06 #2
John Salerno wrote:
What is the best way of altering something (in my case, a file) while
you are iterating over it? I've tried this before by accident and got an
error, naturally.

I'm trying to read the lines of a file and remove all the blank ones.
One solution I tried is to open the file and use readlines(), then copy
that list into another variable, but this doesn't seem very efficient to
have two variables representing the file.


If the file is huge, this can be a problem. But you cannot modify a text
file in place anyway.

For the general case, the best way to go would probably be an iterator:

def iterfilter(file Obj):
for line in fileObj:
if line.strip():
yield line
f = open(path, 'r')
for line in iterfilter(f):
doSomethingWith (line)

Now if what you want to do is just to rewrite the file without the blank
files, you need to use a second file:

fin = open(path, 'r')
fout = open(temp, 'w')
for line in fin:
if line.strip():
fout.write(line )
fin.close()
fout.close()

then delete path and rename temp, and you're done. And yes, this is
actually the canonical way to do this !-)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 19 '06 #3
bruno at modulix wrote:
Now if what you want to do is just to rewrite the file without the blank
files, you need to use a second file:

fin = open(path, 'r')
fout = open(temp, 'w')
for line in fin:
if line.strip():
fout.write(line )
fin.close()
fout.close()

then delete path and rename temp, and you're done. And yes, this is
actually the canonical way to do this !-)


Thanks, that's what I want. Seems a little strange, but at least you
showed me that line.strip() is far better than line == '\n'
May 19 '06 #4
"John Salerno" <jo******@NOSPA Mgmail.com> wrote in message
news:D%******** **********@news .tufts.edu...
John Salerno wrote:
What is the best way of altering something (in my case, a file) while
you are iterating over it? I've tried this before by accident and got an
error, naturally.

I'm trying to read the lines of a file and remove all the blank ones.
One solution I tried is to open the file and use readlines(), then copy
that list into another variable, but this doesn't seem very efficient to
have two variables representing the file.

Perhaps there's also some better to do it than this, including using
readlines(), but I'm most interested in just how you edit something as
you are iterating with it.

Thanks.


Slightly new question as well. here's my code:

phonelist = open('file').re adlines()
new_phonelist = phonelist

for line in phonelist:
if line == '\n':
new_phonelist.r emove(line)

import pprint
pprint.pprint(n ew_phonelist)

But I notice that there are still several lines that print out as '\n',
so why doesn't it work for all lines?


Okay, so it looks like you are moving away from modifying a list while
iterating over it. In general this is good practice, that is, it is good
practice to *not* modify a list while iterating over it (although if you
*must* do this, it is possible, just iterate from back-to-front instead of
front to back, so that deletions don't mess up your "next" pointer).

Your coding style is a little dated - are you using an old version of
Python? This style is the old-fashioned way:

noblanklines = []
lines = open("filename. dat").readlines ()
for line in lines:
if line != '\n':
noblanklines.ap pend(lin)

1. open("xxx") still works - not sure if it's even deprecated or not - but
the new style is to use the file class
2. the file class is itself an iterator, so no need to invoke readlines
3. no need for such a simple for loop, a list comprehension will do the
trick - or even a generator expression passed to a list constructor.

So this construct collapses down to:

noblanklines = [ line for line in file("filename. dat") if line != '\n' ]
Now to your question about why '\n' lines persist into your new list. The
answer is - you are STILL UPDATING THE LIST YOUR ARE ITERATING OVER!!!
Here's your code:

new_phonelist = phonelist

for line in phonelist:
if line == '\n':
new_phonelist.r emove(line)

phonelist and new_phonelist are just two names bound to the same list! If
you have two consecutive '\n's in the file (say lines 3 and 4), then
removing the first (line 3) shortens the list by one, so that line 4 becomes
the new line 3. Then you advance to the next line, being line 4, and the
second '\n' has been skipped over.

Also, don't confuse remove with del. new_phonelist.r emove(line) does a
search of new_phonelist for the first matching entry of line. We know line
= '\n' - all this is doing is scanning through new_phonelist and removing
the first occurrence of '\n'. You'd do just as well with:

numEmptyLines = lines.count('\n ')
for i in range( numEmptyLines ):
lines.remove('\ n')

Why didn't I just write this:

for i in range( lines.count('\n ') ):
lines.remove('\ n')

Because lines.count('\n ') would be evaluated every time in the loop,
reducing by one each time because of the line we'd removed. Talk about
sucky performance!

You might also want to strip whitespace from your lines - I expect while you
are removing blank lines, a line composed of all spaces and/or tabs would be
equally removable. Try this:

lines = map(str.rstrip, file("XYZZY.DAT ") )

-- Paul
May 19 '06 #5
Paul McGuire wrote:
Your coding style is a little dated - are you using an old version of
Python? This style is the old-fashioned way:
I'm sure it has more to do with the fact that I'm new to Python, but
what is old-fashioned about open()? Does file() do anything different? I
know they are synonymous, but I like open because it seems like it's
more self-describing than 'file'.
Now to your question about why '\n' lines persist into your new list. The
answer is - you are STILL UPDATING THE LIST YOUR ARE ITERATING OVER!!!
Doh! I see that now! :)

You might also want to strip whitespace from your lines


Another good hint. Thanks for the reply!
May 19 '06 #6
Paul McGuire wrote:
Your coding style is a little dated - are you using an old version of
Python? This style is the old-fashioned way: [clip] 1. open("xxx") still works - not sure if it's even deprecated or not - but
the new style is to use the file class

Python 2.3.4 (#4, Oct 25 2004, 21:40:10)
[GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
py> open is file
True

James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
May 19 '06 #7
"John Salerno" <jo******@NOSPA Mgmail.com> wrote in message
news:WN******** **********@news .tufts.edu...
Paul McGuire wrote:
Your coding style is a little dated - are you using an old version of
Python? This style is the old-fashioned way:


I'm sure it has more to do with the fact that I'm new to Python, but
what is old-fashioned about open()? Does file() do anything different? I
know they are synonymous, but I like open because it seems like it's
more self-describing than 'file'.


I think it is just part of the objectification trend - "f =
open('xyzzy.dat ')" is sort of a functional/verb concept, so it has to return
something, and its something non-objecty like a file handle - urk! Instead,
using "f = file('xyzzy.dat ')" is more of an object construction concept - "I
am creating a file object around 'xyzzy.dat' that I will interact with." In
practice, yes, they both do the same thing. Note though, the asymmetry of
"f = open('blah')" and "f.close()" - there is no "close(f)". I see now in
the help for "file" this statement:

Note: open() is an alias for file().

Sounds like some global namespace pollution that may be up for review come
the new Python millennium (Py3K, that is).
Now to your question about why '\n' lines persist into your new list. The answer is - you are STILL UPDATING THE LIST YOUR ARE ITERATING OVER!!!


Doh! I see that now! :)


Sorry about the ALL CAPS... I think I got a little rant-ish in that last
post, didn't mean to shout. :)

Thanks for being a good sport,
-- Paul
May 19 '06 #8
Paul McGuire wrote:
answer is - you are STILL UPDATING THE LIST YOUR ARE ITERATING OVER!!!

Doh! I see that now! :)


Sorry about the ALL CAPS... I think I got a little rant-ish in that last
post, didn't mean to shout. :)

Thanks for being a good sport,


Heh heh, actually it was the all caps that kept making me read it over
and over until I really knew what you were saying! :)
May 19 '06 #9
Paul McGuire wrote:
I think it is just part of the objectification trend - "f =
open('xyzzy.dat ')" is sort of a functional/verb concept, so it has to return
something, and its something non-objecty like a file handle - urk! Instead,
using "f = file('xyzzy.dat ')" is more of an object construction concept
I see what you mean, but I think that's why I like using open, because I
like having my functions be verbs instead of nouns.
Note though, the asymmetry of
"f = open('blah')" and "f.close()" - there is no "close(f)".


I'm not sure that's a perfect comparison though, because the counterpart
of close(f) would be open(f), and whether you use file() or open(),
neither is taking f as the parameter like close() does, and you aren't
calling close() on 'blah' above.
May 19 '06 #10

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

Similar topics

15
2141
by: Scott Auge | last post by:
I am looking for comments on something that lets me abstract database updates in an object. Lemme explain what I am thinking: Lets say I have an object Person with... SetFirstName() SetLastName()
10
7038
by: mike | last post by:
If I have 2 object arrays like: var txtobj = theform.getElementsByTagName("input"); var selobj = theform.getElementsByTagName("select"); and i want to iterate over them I'd like to combine them and then iterate over them. so I would do something like this below, but that doesn't look right. var bothobj = txtobj+selobj;
4
1469
by: Dixie | last post by:
I wish to be able to do some things to tables in code. 1. Add a field and its properties. 2. Alter the properties of an existing field in a table. 3. Append some extra entries onto the bottom of a table, if they are not already there. Any help would be appreciated. dixie
3
4943
by: Scott | last post by:
I am trying to alter the ForeColor of a TextBox object so that parts of the displayed text are written in various colors. For example, when writing to the TextBox I wish to display parts of the text in red and then other parts of the text in black. Is it possible to do this with the TextBox object or do I need to use the RichTextBox object? Thank you for your help! Scott
0
1156
by: hazz | last post by:
i have an array (or collection if necessary) of Customers with CustomerID and several properties. For each of these Customers I will have a one to many relationship with Customer products. There are separate tables in the database for Buy, Sell, Insurance, etc. I have already gone out to the database to create a collection of customers from that table if they have a status of 'new.'
7
16662
by: Sehboo | last post by:
We have several generic List objects in our project. Some of them have about 1000 items in them. Everytime we have to find something, we have to do a for loop. There is one method which does the searching, but that method receives the object, and the string to search in that object and runs the FOR loop to find the answer. This is taking time because we have to do searching hundres of times. I want to use Hashtable, but the problem...
7
4044
by: =?Utf-8?B?RXZhbiBSZXlub2xkcw==?= | last post by:
I am a C++ programmer and have been learning C#. I have constructed a List<> and I want to iterate over it, altering each string in the list. In C++, I'd just create an iterator and walk the list, so I was looking for something similar in C#. I looked at foreach, List.ForEach, and IEnumerator. The problem is that all of them seem to return readonly pointers to the items in the List. Therefore I can't alter the list. So I'm using a for...
2
5910
by: chris fellows | last post by:
In VS2005 (C#) I want to set the properties of an object dynamically at runtime from an XML configuration file but without having to know the property name when writing the code. The properties are user-defined classes so I need to be able to iterate through the properties of each sub-object and set the property accordingly. For example, Instead of having to write the code MyObject.SubObjectOne.MyStringProperty = "Some text" I will...
3
6885
Kelicula
by: Kelicula | last post by:
Hi all, I am usually a Perl programmer, I have some background in javascript and am attempting to create a Googleish selector div. Please bear with me, excuse the long introduction... Here's the details: Our site filters content by location. I use zip codes to find radius's. So if a user wants to see content from a location that they don't know the zip code for, I have set up this neat little input field that allows you to type the...
0
8380
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
8296
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
8816
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
8710
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
8598
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
5627
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();...
0
4299
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1928
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1598
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.