teaLeef
teaLeef

Reputation: 1989

Writing csv with python

I wrote a python script in which I generate a csv from numbers I computed.

The rows I write are:

writeRow = [str(t), len(c) , {k for k in c.keys()}, {k for k in c.values()}]

I have two problems:

  1. t is a number that can begin by 0. But in that case, the 0 is deleted. I tried without str() but it doesn't change...

  2. the sets are printed as sets in the cells. However, I want to write these numbers separated by commas in the same cell and without the {} How can I do that?

edit

I am using the csv module; In the code, I create lists for each row to write and then write them with csv.writerow

I'm gonna post more code:

from csv import reader, writer
with open(fileName1) as inp, open(fileName2,'w') as o:

I then define the reader, writer, and the variables t,c

writeRow = [str(t), len(c) , {k for k in c.keys()}, {k for k in c.values()}]

Then I write the result in the output file

Edit form of t and what a row should look like

t = 023 t = 123 t is an int

The line in the end should look like:

cell1  cell2         cell3       cell4 
123    2     string1,string2    num1,num2

string1 and str2 are the dict keys; num1,num2 the corresponding values

Upvotes: 0

Views: 299

Answers (3)

desired login
desired login

Reputation: 1190

Use string formatting for the padding with 0s, and join for the sets:

writeRow = ['{:0>3}'.format(t), len(c) , ','.join(c.keys()), ','.join(c.values())]

note that you should not enter your value for t with a leading 0:

>>>t = 023
>>>t
19

Upvotes: 1

Alexander L. Belikoff
Alexander L. Belikoff

Reputation: 5721

For starters, you can take advantage of the join() method (assuming keys and values are strings):

",".join(c.keys()) + "," + ",".join(c.values())

This will take care of commas. However, this will break very easily for any non-trivial data, so consider using csv module instead, which would take care of escaping dangerous characters.

Upvotes: 2

DanHickstein
DanHickstein

Reputation: 6948

What about using format strings?

'%s,%i'%(t,c) 

might do what you want. You could also use '%03i' or something similar to produce some padding zeros before your number. Or, I might misunderstand your question. Try posting a more complete (runnable) example.

Upvotes: 1

Related Questions