简体   繁体   中英

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 most of the time it doesn't! I remember I used writerow previously and it was working just fine, what am I missing here?

To make the problem clearer: the csv file remains empty although the above code is executed without any errors

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.

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]: with open('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.

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.

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

    next(file1)

    count = 0
    for row in file1:
        while count < 1:
            print(row)  
            count +=1

            with open("newfile.csv", 'w', newline = '') as outfile:
                csv_writer = csv.writer(outfile, delimiter = ',')
                for lines in file1:
                    csv_writer.writerow(lines)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM