【问题标题】:Delete first two rows of a huge csv file using python使用python删除一个巨大的csv文件的前两行
【发布时间】:2020-04-10 21:51:44
【问题描述】:

我想用python删除一个巨大的csv文件(3GB)的标题和第一行,性能很好。

import csv
import pandas as pd

def remove2rows(csv_file):
    data = pd.read_csv(csv_file)
    data = data.iloc[1:]
    data.to_csv(csv_file, header=None, index=False)

if __name__ == "__main__":
    remove2rows(filename)

此脚本有效,但需要一些时间,可能是因为它读取整个文件并将从第 3 行开始到文件末尾的每一行写入一个新的 csv 文件。

有什么方法可以提高性能吗?

【问题讨论】:

  • 不是 Python,但很可能更快:stackoverflow.com/questions/9633114/…
  • 嗨,欢迎来到 SO!堆栈溢出可以帮助您处理通常不起作用的代码。如果您正在寻找要审查的代码,并且想了解改进,请查看codereview.stackexchange.com
  • @petezurich 是的,我也找到了这个网站。我正在尝试在 python 中使用“sed”命令,import subprocess def testing(filename): cmd = "sed -i '' 1d %s" %filename subprocess.call(cmd, shell=True) 错误消息:'sed' 未被识别为内部或外部命令、可运行程序或批处理文件。
  • 您是否确定已安装 sed 并且可以从您的 shell 执行?

标签: python csv


【解决方案1】:

问题:删除一个巨大的csv文件的前两行

这个例子做
找到第二个NewLine的偏移量,把文件位置改成它,复制到文件末尾。

如果您的性能有所改善,请报告!


参考

import io, shutil

DATA = b"""First line to be skipped
Second line to be skipped
Data Line 1
Data Line 2
Data Line 3
"""

def main():    
    # with open('in_filename', 'rb') as in_fh, open('out_filename', 'wb') as out_fh:
    with io.BytesIO(DATA) as in_fh, io.BytesIO() as out_fh:

        # Find the offset of the second NewLine
        # Assuming it within the first 70 bytes
        # Assuming NO embeded NewLine
        # Adjust it to your needs
        buffer = in_fh.read(70)

        offset = 0
        for n in range(2):
            offset = buffer.find(b'\n', offset) + 1

        print('Change the file position to: {}'.format(offset))
        in_fh.seek(offset)

        # Copy to the end of the file
        shutil.copyfileobj(in_fh, out_fh)

        # This is only for demo printing the result
        print(out_fh.getvalue())

if __name__ == "__main__":
    main()

输出

Change the file position to: 59
b'Data Line 1\nData Line 2\nData Line 3\n'

用 Python 测试:3.5

【讨论】:

    【解决方案2】:

    请注意,“从文件中删除行”的唯一方法是读取整个文件(尽管不一定一次全部 xD)并将选定的行写回新文件。这就是文件的工作方式。

    但是在这里不使用 panda 肯定会节省时间 - panda 是一种用于对表格数据进行计算的工具,而不是文件实用程序。使用 stdlib 的 csv 模块或更简单地使用纯文件功能(如果您 101% 确定您的 csv 不包含嵌入的换行符)可能会更有效,至少 wrt/ 内存使用,并且可能 wrt/ 原始性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2019-01-30
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多