如何将数据添加到 CSV 文件的末尾 (Python)
我需要能够定期将数据添加到 CSV 文件的末尾。理想情况下,我希望在不将整个文件读入内存的情况下执行此操作。
有没有办法可以将数据附加到文件末尾?我想到的一个解决方案是简单地从 Python 中提取一个管道命令,但这似乎是一种丑陋的黑客行为。有没有更好的方法可以在 CSV 文件末尾追加一行或几行?
I need to be able to periodically add data to the end of a CSV file. Ideally, I would like to do this without reading the entire file into memory.
Is there a way where I can append data to the end of a file?. One solution that occured to me was to simply shell a pipe command from Python, but that seemed too much of an ugly hack. is there a better way to append a line or maybe a few lines to the end of a CSV file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,有两种方法。首先,您可以
open(filename, 'ab')
,这将打开以二进制模式附加。第二个是使用 seek :(我主要把第二个放在那里所以我不只是抄袭 S. Lott 和 SilentGhost,这并不是特别有用。)
Actually, there are two approaches. First, you can just
open(filename, 'ab')
, which will open the file for appending in binary mode. The second is using seek:(I threw that second one in there mainly so I wasn't just ripping off S. Lott and SilentGhost. It's not particularly useful.)