开发者

Python: problems with csvwriter

开发者 https://www.devze.com 2023-01-23 12:26 出处:网络
I am attempting to write data (mostly dates, booleans and float data types) into a CSV file format. Here is a snippet of my code:

I am attempting to write data (mostly dates, booleans and float data types) into a CSV file format. Here is a snippet of my code:

# Write data to file
with open(OUTPUT_DIR + output_filename,'w') as outputfile:
    wrtr = cs开发者_如何学Pythonv.writer(outputfile, delimiter=',', quotechar='"')

    for x, y in datarows.items():
        a,b,c,d,e,f,g = (somedate.strft('%Y-%m-%d'),0,6058.7,False,1913736200,0,False)                     
        rowstr = "{0},{1},{2},{3},{4},{5},{6}".format(a,b,c,d,e,f,g)
        wrtr.writerow(rowstr)

    outputfile.close()

File contents look like this:

2,0,0,7,-,10,-,03,",",0,",",6,0,5,8,.,7,",",F,a,l,s,e,",",1,9,1,3,7,3,6,2,0,0,",",0,",",F,a,l,s,e

I am currently using the raw file object to write to file - but I would prefer to use the csvwrite - since that is what its supposed to be used for


Try wrtr.writerow([a,b,c,d,e,f,g]) instead.

writerow() parameter must be a list of values, not a text line. The idea of csv.writer is that it will format row values according to CSV rules.

The result you have is due to the fact that writerow() interpreted your rowstr string as a list of characters.


look at this example maybe it can help you:

import datetime

with open('file.csv','w') as outputfile:
    wrtr = csv.writer(outputfile, delimiter=',', quotechar='"')
    a = (datetime.datetime.now().strftime('%Y-%m-%d'),0,6058.7,False,1913736200,0,False)
    wrtr.writerow(a)  # pass an iterable here

    # outputfile.close() you don't have to call close() because you use with

file.csv

2010-11-01,0,6058.7,False,1913736200,0,False

hope this can help you

0

精彩评论

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