2

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 = csv.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

3
  • Can you clarify what your problem is? Commented Nov 1, 2010 at 13:51
  • that's an awful code, why are you closing outputfile when you're using with statement? what this datarows for loop is for? Commented Nov 1, 2010 at 13:56
  • @Mike, @Michael, each character became a separate value in CSV, so instead of 7 columns there are many more. Commented Nov 1, 2010 at 13:59

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.