![](/img/trans.png)
[英]When I write to a CSV file in Python, it copies part of the last row and writes it to the bottom of the file
[英]When I write into CSV file, it writes only the second time
我在学习过程中,我遇到了这个问题..
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中的值! 我哪里出错了? 拜托,赐教。
您没有在最后关闭底层文件,因此数据不会被刷新。 此外,您应使用“b”标志以确保以二进制模式打开文件。 ( http://docs.python.org/library/csv.html#csv.writer )使用:
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.
您可能希望使用with语句来确保一旦完成就将所有内容写入fileobj。
with open('db.csv','wb') as fi:
writer = csv.writer(fi)
当然,你不会在一些早期的蟒蛇中使用,但你总能在将来导入它
from __future__ import with_statement
编辑:更改为以二进制模式打开,感谢您指出。
也许你的sql第一次返回一个空字符串? 这不是csv模块的问题,只需使用你的第一行和最后一行而不是cur_baseboard
,写一个随机文本,你会发现它总是会被写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.