简体   繁体   中英

When I write into CSV file, it writes only the second time

I am in the learning process and I face this problem..

writer = csv.writer(open("db.csv", "w"))
connection = sqlite3.connect('hx.db')
cur_baseboard = connection.cursor()
cur_baseboard.execute('select * from baseboard')
writer.writerows(cur_baseboard)

When I run this code, the first time it creates the csv file db.csv, but writes nothing in it. After I run it the second time, it fills with the values in db! Where did I went wrong? Please, enlighten me.

You're not closing the underlying file at the end, so the data is not flushed. Also, you should use the "b" flag to make sure the file is opened in binary mode. ( http://docs.python.org/library/csv.html#csv.writer ) Use:

from __future__ import with_statement
with open("db.csv", "wb") as f:
    writer = csv.writer(f)
    [...]
# File is closed automatically after end of with block.

You may want to use the with statement to ensure that everything gets written to the fileobj as soon as its finished.

with open('db.csv','wb') as fi:
    writer = csv.writer(fi)

Of course you won't have with in some of the earlier pythons but you can always future import it

from __future__ import with_statement

EDIT: Changed to open in binary mode, thanks for pointing that out.

It is perhaps that your sql is returned an empty string for the first time? It is not a problem with csv module, just use your first and last line and instead of cur_baseboard , write a random text and you will find that it will always get written.

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