当我写入 CSV 文件时,它只写入第二次

发布于 2024-10-17 14:07:33 字数 328 浏览 2 评论 0原文

我正在学习过程中,遇到这个问题。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烙印 2024-10-24 14:07:33

您最后没有关闭基础文件,因此数据不会刷新。另外,您应该使用“b”标志来确保文件以二进制模式打开。 ( http://docs.python.org/library/csv.html#csv.作者)使用:

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'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.
彩虹直至黑白 2024-10-24 14:07:33

您可能需要使用 with 语句来确保所有内容在完成后立即写入 fileobj。

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

当然,在一些早期的 python 中你不会有 with ,但你以后总是可以导入它

from __future__ import with_statement

编辑:更改为以二进制模式打开,感谢您指出这一点。

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.

风透绣罗衣 2024-10-24 14:07:33

也许你的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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文