【问题标题】:How can I chop a large and growing CSV file in python如何在 python 中剪切一个大且不断增长的 CSV 文件
【发布时间】:2022-01-17 05:25:12
【问题描述】:

我有一个如下所示的 grow.csv 文件:

...
20211213 20:49:01,61826.0,61925.0,61928.0,1014.41
20211213 20:50:01,61839.0,62122.0,61928.0,1014.41
20211213 20:51:01,61901.0,62026.0,62035.0,1015.03
...

但我想将此文件保持在最新状态,例如 ~10,000 行/行,因为程序使用了最后 ~7,500 行。有没有一种聪明的方法可以做到这一点?

【问题讨论】:

  • 哈哈哈....对不起,我忘记了这些编辑器是如何工作的。

标签: csv file rows chop


【解决方案1】:

您可以在命令行上使用tail 命令获取文件的最低 10000 行,例如

tail -n 10000 growing.csv > truncated.csv

如果您想要保留标头或顶级 cmets,同样可以使用 head 命令来获取它们:

# write the first line of growing.csv to truncated.csv
# truncated.csv will be overwritten
head -n1 growing.csv > truncated.csv

# Now append the lowest 10k lines to the newly
# created/truncated file
tail -n 10000 growing.csv >> truncated.csv

【讨论】:

  • 谢谢霍尔格。这听起来很简单。是否应将其设置为 n 维护周期。我认为这不应该每分钟运行一次。
  • 这取决于您将数据添加到文件的时间、方式和数量。根据您实际生成数据的方式,甚至可能有更合适的方法来减小数据大小。
猜你喜欢
  • 1970-01-01
  • 2018-07-11
  • 2014-09-12
  • 1970-01-01
  • 2015-02-17
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
  • 2012-07-30
相关资源
最近更新 更多