473,799 Members | 3,270 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

trouble writing results to files

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

Nov 29 '06
16 1819
Steven D'Aprano wrote:
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.
Having the same object in two lists simultaneously does not double the total
amount of memory; you just need space for an extra pointer.
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.
That example was chosen to prove your point. The real contender for the
"swap items" problem are slices.

def swap_slice(item s):
left = items[::2]
items[::2] = items[1::2]
items[1::2] = left
return items

def swap_loop(items ):
for i in xrange(0, len(items)-1, 2):
k = i+1
items[i], items[k] = items[k], items[i]
return items

$ python2.5 -m timeit -s 'from swap import swap_loop as swap; r =
range(10**6)' 'swap(r)'
10 loops, best of 3: 326 msec per loop
$ python2.5 -m timeit -s 'from swap import swap_slice as swap; r =
range(10**6)' 'swap(r)'
10 loops, best of 3: 186 msec per loop

$ python2.5 -m timeit -s 'from swap import swap_loop as swap; r =
range(10**7)' 'swap(r)'
10 loops, best of 3: 3.27 sec per loop
$ python2.5 -m timeit -s 'from swap import swap_slice as swap; r =
range(10**7)' 'swap(r)'
10 loops, best of 3: 2.29 sec per loop

With 10**7 items in the list I hear disc access on my system, so the
theoretical sweet spot where swap_slice() is already swapping while
swap_loop() is not may be nonexistent...

Peter

Nov 30 '06 #11
Peter Otten <__*******@web. dewrote:
That example was chosen to prove your point. The real contender for the
"swap items" problem are slices.

def swap_slice(item s):
left = items[::2]
items[::2] = items[1::2]
items[1::2] = left
return items
It makes no difference to the time or memory use, but you can of course
also write swap_slice using the aforementioned 'well known idiom':

items[::2], items[1::2] = items[1::2], items[::2]

Nov 30 '06 #12
Duncan Booth wrote:
items[::2], items[1::2] = items[1::2], items[::2]
Cool. I really should have found that myself.

Peter

Nov 30 '06 #13
On Thu, 30 Nov 2006 11:17:17 +0100, Peter Otten wrote:
Steven D'Aprano wrote:
>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.

Having the same object in two lists simultaneously does not double the total
amount of memory; you just need space for an extra pointer.
Sure. But if you have millions of items in a list, the pointers themselves
take millions of bytes -- otherwise known as megabytes.
[snip]
>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.

That example was chosen to prove your point.
Well, I thought about choosing an example that disproved my point, but I
couldn't think of one :-)
The real contender for the "swap items" problem are slices.

def swap_slice(item s):
left = items[::2]
items[::2] = items[1::2]
items[1::2] = left
return items
I always forget that extended slices can be assigned to as well as
assigned from! Nice piece of code... if only it worked.
>>def swap_slice(item s):
.... left = items[::2]
.... items[::2] = items[1::2]
.... items[1::2] = left
.... return items
....
>>alist
[0, 1, 2, 3, 4]
>>swap_slice(al ist)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in swap_slice
ValueError: attempt to assign sequence of size 2 to extended slice of size 3

Everybody always forgets corner cases... like lists with odd number of
items... *wink*

Here is a version that handles both odd and even length lists:

def swap_slice(item s):
left = items[:len(items)-1:2]
items[:len(items)-1:2] = items[1::2]
items[1::2] = left
return items
Replacing the explicit Python for loop with an implicit loop in C makes it
very much faster.
--
Steven.

Nov 30 '06 #14
Steven D'Aprano <st***@REMOVE.T HIS.cybersource .com.auwrote:
Everybody always forgets corner cases... like lists with odd number of
items... *wink*
I didn't forget. I just assumed that raising an exception was a more useful
response.
Here is a version that handles both odd and even length lists:

def swap_slice(item s):
left = items[:len(items)-1:2]
items[:len(items)-1:2] = items[1::2]
items[1::2] = left
return items
I guess a viable alternative to raising an exception would be to pad the
list to even length:

[1, 2, 3] -[2, 1, Padding, 3]

for some value of Padding. I don't think I would expect swap_slice to
silently fail to swap the last element.
Nov 30 '06 #15
Steven D'Aprano wrote:
On Thu, 30 Nov 2006 11:17:17 +0100, Peter Otten wrote:
>Steven D'Aprano wrote:
>>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.

Having the same object in two lists simultaneously does not double the
total amount of memory; you just need space for an extra pointer.

Sure. But if you have millions of items in a list, the pointers themselves
take millions of bytes -- otherwise known as megabytes.
I don't know the exact layout of an int, but let's assume 4 bytes for the
class, the value, the refcount and the initial list entry -- which gives
you 16 bytes per entry for what is probably the class with the smallest
footprint in the python universe. For the range(N) example the slicing
approach then needs an extra 4 bytes or 25 percent. On the other hand, if
you are not dealing with unique objects (say range(100) * (N//100)) the
amount of memory for the actual objects is negligable and consequently the
total amount doubles.
You should at least take that difference into account when you choose the
swapping algorithm.
>That example was chosen to prove your point.
Well, I thought about choosing an example that disproved my point, but I
couldn't think of one :-)
Lack of fantasy :-)
>The real contender for the "swap items" problem are slices.

def swap_slice(item s):
left = items[::2]
items[::2] = items[1::2]
items[1::2] = left
return items

I always forget that extended slices can be assigned to as well as
assigned from! Nice piece of code... if only it worked.
>>>def swap_slice(item s):
... left = items[::2]
... items[::2] = items[1::2]
... items[1::2] = left
... return items
...
>>>alist
[0, 1, 2, 3, 4]
>>>swap_slice(a list)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in swap_slice
ValueError: attempt to assign sequence of size 2 to extended slice of size
3

Everybody always forgets corner cases... like lists with odd number of
items... *wink*
True in general, but on that one I'm with Duncan.

Here is another implementation that cuts maximum memory down from 100 to
50%.

from itertools import islice
def swap(items):
items[::2], items[1::2] = islice(items, 1, None, 2), items[::2]
return items

Peter
Dec 1 '06 #16
Peter Otten wrote:
Here is another implementation that cuts maximum memory down from 100 to
50%.

from itertools import islice
def swap(items):
****items[::2],*items[1::2]*=*islice(items ,*1,*None,*2),* items[::2]
****return*item s
Unfortunately, the following
>>a = [1, 2, 3]
a[::2] = iter([10, 20, 30])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2
>>a
[1, 2, 3]

does not support my bold claim :-( Since the list is not changed there must
be an intermediate copy.

Peter
Dec 1 '06 #17

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

Similar topics

9
4966
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...
13
2123
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
16
1610
by: mikelinyoho | last post by:
Regards: Where the code trouble is? #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <string.h>
6
2086
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: > ====================================================== >
59
7528
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
0
1266
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...
27
2026
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...
1
2046
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...
5
13387
matheussousuke
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.
0
9544
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,...
1
10238
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9077
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
7570
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
6809
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
5467
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...
1
4145
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
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.