当我写入 CSV 文件时,它只写入第二次
我正在学习过程中,遇到这个问题。
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)
当我运行此代码时,它第一次创建 csv 文件 db.csv,但在其中不写入任何内容。 第二次运行后,它填充了 db 中的值! 我哪里做错了?请赐教。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您最后没有关闭基础文件,因此数据不会刷新。另外,您应该使用“b”标志来确保文件以二进制模式打开。 ( http://docs.python.org/library/csv.html#csv.作者)使用:
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:
您可能需要使用 with 语句来确保所有内容在完成后立即写入 fileobj。
当然,在一些早期的 python 中你不会有 with ,但你以后总是可以导入它
编辑:更改为以二进制模式打开,感谢您指出这一点。
You may want to use the with statement to ensure that everything gets written to the fileobj as soon as its finished.
Of course you won't have with in some of the earlier pythons but you can always future import it
EDIT: Changed to open in binary mode, thanks for pointing that out.
也许你的sql第一次返回空字符串?这不是 csv 模块的问题,只需使用您的第一行和最后一行,而不是
cur_baseboard
,写入随机文本,您会发现它总是会被写入。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.