Random ...
 
December 2017
S M T W T F S
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            
Tags ...
Links



python+zope++:: csv problem: getting odd or even
Posted at 05.Jun,2006 21:09  Comments 2 / Trackbacks 0 / Like this post!
Technorati tag(s):

Somebody came to me with an excel file caontaining 50000+ records. She wanted to divide the data sets into two; the even rows in one file and the odd on another.

I didn't bother with the reasons she wanted it that way and whipped out my notebook.

Here's what I came out within two minutes. No scripts, just did it in the interpreter.:

  >>> import csv
  >>> f=open('thefile','rb') #open the excel file
  >>> oddf = open('odd','a') #open the odd file
  >>> evenf = open('even','a') #open the even file
  >>> c=0 # set counter
  >>> for i in csv.reader(f):
  ...       if divmod(c,2)[1] == 0:
  ...          s=''.join(i)
  ...          evenf.write(s+'\n')
  ...       else:
  ...          s=''.join(i)
  ...          oddf.write(s+'\n')
  ...       c=c+1
  ...

Not elegant, but workable. How would you have done it?


Bookmark and Share

Is this entry helpful? Comments/Donate/Click some google ads.  
Trackback is http://myzope.kedai.com.my/blogs/kedai/84/tbping 

Comments

Quick observation: you should use enumerate function to replace the counter and be more pythonic.

Rocky Burt  at 05.Jun,2006 23:58
enumerate

thanks for the pointer. I have never find the reason to use enumerate().

I do now.

so is this:

import csv
f=open('thefile','rb')
oddf=open('odd','a')
evenf=open('even','a')

e=enumerate(f)
for k,v in e:
....if divmod(k,2)[1] == 0:
........evenf.write(k+'\n')
....else:
........oddf.write(k+'\n')




kedai  at 06.Jun,2006 09:53
Post a comment