From: Chris Rebert on
On Thu, Jul 8, 2010 at 4:30 AM, Dlanor Slegov
<dlanorslegov(a)rocketmail.com> wrote:
> Hi,
>
> I am trying to find a python solution for an informatics problem I have at
> work. Generalized equivalent of my problem is:
>
> I have an excel sheet with column 1 and column 2 having corresponding
> information (much like a dictionary, however with repeating "keys"). Its
> like if you read down column 1: a,b,a,a,b,c and if you read down column 2:
> 1,2,3,4,5,6. I would like to write "unique" files such as a.txt, b.txt and
> c.txt with matching information (from column 2) in a.txt in separate rows
> like: 1,3,4 and in b.txt like: 2,5, etc.
>
> What I have been able to do until now is the following:
>
> import sys
> sys.path.append("C:/Downloads/Python/xlrd-0.6.1")
> import xlrd
>
> wb = xlrd.open_workbook("myexcelsheet.xls")
> sheet = wb.sheet_by_index(0)
>
> clmn1 = sheet.col_values(1,1)
> clmn2 = sheet.col_values(2,1)
>
> #NOW WHAT IS HAVE ARE TWO LISTS WITH CORRESPONDING INDICES
>
> #My thought is now to write a counter and for each value in clmn1, write a
> text file with the name of the value and add data from clmn2 in this file.. I
> want to start with index[0], i.e. value 1 of clmn1 and then go to 2nd value
> and compare (==) it with 1st value and if its equal then append to the same
> file 2nd value from clmn2...like this with 3rd value in clmn1, i want to
> compare it to 1st and 2nd value....wrap this whole in to a nice loop.
>
> #Don't know if this is the "easy" way, but this is what my mind came up
> with. Now I am stuck in colored line below, where I am unable to "create a
> new filename with string coming from a variable":
>
> l = len(clmn1)
> c = 0
> while (c < l):
> filename = clmn1[c]
> fhdl1 = open('/mypythonfolder/%(filename)s_appendsomename.txt','w')

fhdl1 = open('/mypythonfolder/%s_appendsomename.txt' % filename,'w')

> fhdl1.write(clmn2(c)+'\n')
> print filename
> ...
> c = c + 1

Personally, I'd rewrite the loop like this, using zip() and a for-loop:

for name, value in zip(clmn1, clmn2):
filepath = '/mypythonfolder/' + name + '_appendsomename.txt'
with open(filepath, 'a') as f:
f.write(str(value))
f.write('\n')

Cheers,
Chris
--
http://blog.rebertia.com