Skip to content Skip to sidebar Skip to footer

Csv's Writerow In Python Doesn't Work Most Of The Time

I have some very simple piece of code: import csv out = csv.writer(open('test.csv', 'wb'), delimiter=',') out.writerow([u'value1', u'value2', u'value3']) It sometimes works, but m

Solution 1:

I modified the code to look as follows:

import csv
f = open('test.csv', 'wb')
out = csv.writer(f, delimiter=",")
out.writerow([u"value1", u"value2", u"value3"])
f.close()

So all I've done is that I separated the open('test.csv', 'wb') and assigned it to f, so that I can use f.close() at the end. It works perfectly this way.

Solution 2:

A slightly more Pythonic way of accomplishing what you're doing is to use a context manager, which is designated by the with statement:

In [1]: import csv

In [2]: withopen('test.csv', 'wb') as f:
   ...:     writer = csv.writer(f)
   ...:     writer.writerow([u"value1", u"value2", u"value3"])

When you use with, among other things, it ensures that the file is properly closed when the code exits the indented block. Also, when using the csv module, the default delimiter is ,, so you can actually omit that from your writer (or out, in your case) declaration.

Solution 3:

I resolved the issue by focusing on how I was indenting the block which contained the csv.writer. I indented it in more, under some other iteration that I had done after reading it in.

withopen('retrans.csv') as csvfile:
    file1 = csv.reader(csvfile, delimiter = ',')
    print(file1)

    next(file1)

    count = 0for row in file1:
        while count < 1:
            print(row)  
            count +=1withopen("newfile.csv", 'w', newline = '') as outfile:
                csv_writer = csv.writer(outfile, delimiter = ',')
                for lines in file1:
                    csv_writer.writerow(lines)

Post a Comment for "Csv's Writerow In Python Doesn't Work Most Of The Time"