开发者

Writing CSV values to file results in values being separated in single characters (Python)

Kinda knew to Python:

I have the following code:

def printCSV(output, values, header):
 63     """
 64         prints the output data as comma-separated values
 65     """
 66 
 67     try:
 68         with open(output, 'w') as csvFile:
 69             #print headers
 70             csvFile.write(header)
 71 
 72             for value in values:
 73                 #print value, "\n"
 74                 csvFile.write(",".join(value))
 75                 csvFile.write("\n")
 76     except:
 77        print "Error occured while writing CSV file..."



Values is a list constructed somewhat like this:

values = []

for i in range(0,5):
    row = "A,%s,%s,%s" % (0,stringval, intval)
    values.append(row)

When I open the file created by the above function, I expect to see something like this:

Col1,Col2,Col3,Col4
A,0,'hello',123
A,0,'foobar',42

Instead, I am seeing data like this:

Col1,Col2,Col3,Col4
A,0,'h','e','l','l','o',1,2,3
A,0,'f','o','o','b','a','r',4,2

Anyone knows what is causing this?

I even tried to use fopen and fwrite() directly, still the same problem exists.

Whats 开发者_Go百科causing this?


The problem you're encountering is that you're doing ",".join(value) with value being a string. Strings act like a collection of characters, so the command translates to "Join each character with a comma."

What you could do instead is use a tuple instead of a string for your row values you pass to printCSV, like this:

values = []

for i in range(0,5):
    row = ('A', 0, stringval, intval)
    values.append(row)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜