I have two semi related questions...
First, I am trying to output a list of strings to a csv file using the
csv module. The output file separates each letter of the string with a
comma and then puts each string on a separate line. So the code is:
import csv
output = csv.writer(open ('/Python25/working/output.csv', 'a'))
a = ["apple", "cranberry" , "tart"]
for elem in range(len(a)):
output.writerow (a[elem])
.... and it would write to the file:
a,p,p,l,e
c,r,a,n,b,e,r,r ,y
t,a,r,t
How do I get it to write "apple", "cranberry" , "tart" ?
Second, there is a significant delay (5-10 minutes) between when the
program finishes running and when the text actually appears in the
file. Any ideas for why this happens? It is the same for writing with
the csv module or the standard way.
thanks!
Lisa 16 1815 li**********@gm ail.com wrote:
import csv
output = csv.writer(open ('/Python25/working/output.csv', 'a'))
a = ["apple", "cranberry" , "tart"]
for elem in range(len(a)):
output.writerow (a[elem])
output.writerow expects a sequence as an argument. You are passing a
string, which is a sequence of characters. By the way, what output are you
expecting to get? Do you want a file with only one line (apple,
cranberry, tart), or each fruit in a different line?
BTW, iterating over range(len(a)) is an anti-pattern in Python. You should
do it like this:
for item in a:
output.writerow ([item])
Second, there is a significant delay (5-10 minutes) between when the
program finishes running and when the text actually appears in the
file.
Try closing the file explicitly.
Cheers,
--
Roberto Bonvallet
On 2006-11-29, Roberto Bonvallet <Ro************ ***@cern.chwrot e:
BTW, iterating over range(len(a)) is an anti-pattern in Python.
Unless you're modifying elements of a, surely?
--
Neil Cerutti
You can't give him that cutback lane. He's so fast, and he sees it so well. He
can also run away from you if he gets a little bit of crack. --Dick Lebeau
Neil Cerutti wrote:
On 2006-11-29, Roberto Bonvallet <Ro************ ***@cern.chwrot e:
>BTW, iterating over range(len(a)) is an anti-pattern in Python.
Unless you're modifying elements of a, surely?
enumerate is your friend :)
for n, item in enumerate(a):
if f(item):
a[n] = whatever
--
Roberto Bonvallet
On 2006-11-29, Roberto Bonvallet <Ro************ ***@cern.chwrot e:
Neil Cerutti wrote:
>On 2006-11-29, Roberto Bonvallet <Ro************ ***@cern.chwrot e:
>>BTW, iterating over range(len(a)) is an anti-pattern in Python.
Unless you're modifying elements of a, surely?
enumerate is your friend :)
for n, item in enumerate(a):
if f(item):
a[n] = whatever
I was going to bring it up but I had a brainfart about the order
of (n, item) in the tuple and was too lazy to look it up. ;-)
--
Neil Cerutti
Neil Cerutti wrote:
>BTW, iterating over range(len(a)) is an anti-pattern in Python.
Unless you're modifying elements of a, surely?
and needs to run on a Python version that doesn't support enumerate.
</F>
Roberto Bonvallet wrote:
li**********@gm ail.com wrote:
import csv
output = csv.writer(open ('/Python25/working/output.csv', 'a'))
a = ["apple", "cranberry" , "tart"]
for elem in range(len(a)):
output.writerow (a[elem])
output.writerow expects a sequence as an argument. You are passing a
string, which is a sequence of characters. By the way, what output are you
expecting to get? Do you want a file with only one line (apple,
cranberry, tart), or each fruit in a different line?
I want it to print everything on one line and then create a new line
where it will print some more stuff. In my real program I am iterating
and it will eventually print the list a couple hundred times. But it
would be useful to understand how to tell it to do either.
BTW, iterating over range(len(a)) is an anti-pattern in Python. You should
do it like this:
for item in a:
output.writerow ([item])
I can try that. Is using range(len(a)) a bad solution in the sense
that its likely to create an unexpected error? Or because there is a
more efficient way to accomplish the same thing?
thanks!
Lisa li**********@gm ail.com wrote:
I can try that. Is using range(len(a)) a bad solution in the sense
that its likely to create an unexpected error? Or because there is a
more efficient way to accomplish the same thing?
for-in uses an internal index counter to fetch items from the sequence, so
for item in seq:
function(item)
is simply a shorter and more efficient way to write
for item in range(len(seq)) :
function(seq[item])
also see this article: http://online.effbot.org/2006_11_01_archive.htm#for
</F>
On Wed, 29 Nov 2006 17:00:30 +0100, Fredrik Lundh wrote:
Neil Cerutti wrote:
>>BTW, iterating over range(len(a)) is an anti-pattern in Python.
Unless you're modifying elements of a, surely?
and needs to run on a Python version that doesn't support enumerate.
This isn't meant as an argument against using enumerate in the common
case, but there are circumstances where iterating with an index variable
is the right thing to do. "Anti-pattern" tends to imply that it is always
wrong.
The advantage of enumerate disappears if you only need to do something to
certain items, not all of them:
>>alist = list("abcdefghi j") for i in xrange(3, 7, 2):
.... print i, alist[i]
....
3 d
5 f
Nice and clear. But this is just ugly and wasteful:
>>for i,c in enumerate(alist ):
.... if i in xrange(3, 7, 2):
.... print i, c
....
3 d
5 f
although better than the naive alternative using slicing, which is just
wrong:
>>for i,c in enumerate(alist[3:7:2]):
.... print i, c
....
0 d
1 f
The indexes point to the wrong place in the original, non-sliced list, so
if you need to modify the original, you have to adjust the indexes by hand:
>>for i,c in enumerate(alist[3:7:2]):
.... print 2*i+3, c
....
3 d
5 f
And remember that if alist is truly huge, you may take a performance hit
due to duplicating all those megabytes of data when you slice it. If you
are modifying the original, better to skip making a slice.
I wrote a piece of code the other day that had to walk along a list,
swapping adjacent elements like this:
for i in xrange(0, len(alist)-1, 2):
alist[i], alist[i+1] = alist[i+1], alist[i]
The version using enumerate is no improvement:
for i, x in enumerate(alist[0:len(alist)-1:2]):
alist[i*2], alist[i*2+1] = alist[i*2+1], x
In my opinion, it actually is harder to understand what it is doing.
Swapping two items using "a,b = b,a" is a well known and easily recognised
idiom. Swapping two items using "a,b = b,c" is not.
--
Steven.
Steven D'Aprano wrote:
On Wed, 29 Nov 2006 17:00:30 +0100, Fredrik Lundh wrote:
>Neil Cerutti wrote:
>>>BTW, iterating over range(len(a)) is an anti-pattern in Python.
Unless you're modifying elements of a, surely?
and needs to run on a Python version that doesn't support enumerate.
This isn't meant as an argument against using enumerate in the common
case, but there are circumstances where iterating with an index variable
is the right thing to do. "Anti-pattern" tends to imply that it is always
wrong.
Right, I should have said: "iterating over range(len(a)) just to obtain the
elements of a is not the pythonic way to do it".
Cheers,
--
Roberto Bonvallet This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Penn Markham |
last post by:
Hello all,
I am writing a script where I need to use the system() function to call
htpasswd. I can do this just fine on the command line...works great
(see attached file, test.php). When my webserver runs that part of the
script (see attached file, snippet.php), though, it doesn't go through.
I don't get an error message or anything...it just returns a "1"
(whereas it should return a "0") as far as I can tell. I have read the
PHP...
|
by: Martijn van den Branden |
last post by:
Hi,
sorry if this message gets posted twice, i seem to have some problem posting
to newsgroups.
i've rewritten some loop in matlab using the mex interface method in c, and
i've achieved a reduction in calculation time of about five hours :).
however, the resulting arrays
are not the same as with matlab. this is the first time i write something in
c, and i suspect i'm making some
|
by: mikelinyoho |
last post by:
Regards:
Where the code trouble is?
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
|
by: darrel |
last post by:
I'm struggling with an odd permissions problem I have with one of my
functions. It takes a file, writes a directory, and then uploads some files
to it. This works. Once. Any subsequent attempt and writing new files to the
created directory results in an access denied error.
Thanks to a script by Keith Brown, I was able to determine who my
application was running as:
> ======================================================
>
|
by: Rico |
last post by:
Hello,
I have an application that I'm converting to Access 2003 and SQL Server 2005
Express. The application uses extensive use of DAO and the SEEK method on
indexes. I'm having an issue when the recordset opens a table. When I
write
Set rst = db.OpenRecordset("MyTable",dbOpenTable, dbReadOnly)
I get an error. I believe it's invalid operation or invalid parameter, I'm
| |
by: DaveK777 |
last post by:
I'm about to start development on a new project in PHP, which I've
never used before. I got the latest version (5.1.4) installed and
running on my dev/test server, and I tried enabling APC since I'm
definitely going to want to use opcode caching. The apc.php script
runs and indicates that it's caching, but only one file at a time.
Each time I request a different file there's a cache miss, then if I
refresh the browser a few times it gets...
|
by: stonemcstone |
last post by:
I've been programming in C for years, and never experienced troubles
until I started using the new RealC-32, a freeware C compiler from the
same company that makes RealPlayer and Quicktime. That's when the
trouble started. See, RealC-32 is like any other C compiler but with
one notable difference. Any time your code invokes undefined
behavior-- for example by dereferencing an uninitialized pointer--
rather than the usual segmentation...
|
by: John Wright |
last post by:
I am running a console application that connects to an Access database (8
million rows) and converts it to a text file and then cleans and compacts
the database. When it runs I get the following error:
The CLR has been unable to transition from COM context 0x1a2008 to COM
context 0x1a2178 for 60 seconds. The thread that owns the destination
context/apartment is most likely either doing a non pumping wait or
processing a very long...
|
by: matheussousuke |
last post by:
Hello, I'm using tiny MCE plugin on my oscommerce and it is inserting my website URL when I use insert image function in the emails.
The goal is: Make it send the email with the URL http://mghospedagem.com/images/controlpanel.jpg
instead of
http://mghospedagem.comhttp://mghospedagem.com/images/controlpanel.jpg
As u see, there's the website URL before the image URL.
|
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...
|
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...
| |
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...
|
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...
|
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();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |