如何在Python中存储具有行数限制的数据
对于一个项目,我有发送有效负载的设备,我应该将它们存储在本地文件中,但我有内存限制,并且我不想存储超过 2000 个数据行。再次由于内存限制,我无法拥有数据库,因此我选择将数据存储在 csv 文件中。 我尝试使用 open('output.csv', 'r+') as f:
;我将行附加到 csv 的末尾,每次都必须使用 sum(1 for line in f)
检查长度,以确保其不超过 2000。 当我达到 2000 行时,大问题就开始了,我想理想地删除第一行并在末尾添加另一行,或者开始从文件开头写入行并覆盖旧行而不删除所有内容,但我不知道如何去做它。我尝试使用 open('output.csv', 'w+')
或 open('output.csv', 'a+')
但它会删除所有内容使用 w+ 时只写入一行,使用 a+ 时它只是继续追加到末尾。另一方面,我无法再用两者来计算行数。您能帮我一下,我应该使用哪个命令从头开始重写每一行,或者从开头删除一行并在末尾追加一行?如果您能告诉我是否有比 csv 文件更好的选择来存储许多数据,我也将不胜感激,或者我可以使用更好的方法来计算行数。
For a project I have devices who send payloads and I should store them on a localfile, but I have memory limitation and I dont want to store more than 2000 data rows. again for the memory limitation I cannot have a database so I chose to store data in csv file.
I tried to use open('output.csv', 'r+') as f:
; I'm appending the rows to the end of my csv and I have to check each time the lenght with sum(1 for line in f)
to be sure its not more than 2000.
The big problem starts when I reach 2000 rows and I want to ideally delete the first row and add another row to the end or start to write rows from the beginning of the file and overwrite the old rows without deleting evrything, but I dont know how to do it. I tried to use open('output.csv', 'w+')
or open('output.csv', 'a+')
but it will delete all the contents with w+ while writing only one row and by a+ it just continues to append to the end. I on the otherhand I cannot count the number of rows anymore with both. can you pleas help me which command should I use to start to rewrite each line from the beginning or delete one line from the beginning and append one to the end? I will also appriciate if you can tell me if there is a better chioce than csv files for storing many data or I can use a better way to count the number of rows.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这应该有帮助。查看内嵌评论
This should help. See comments inline