【问题标题】:concatenate large (>100MB) multiple (say 10) csv files using python使用python连接大(> 100MB)多个(比如10个)csv文件
【发布时间】:2020-04-20 08:20:34
【问题描述】:

我有 12 个结构相同的大型 csv 文件。 我想将所有 csv 文件合并为单个 csv 文件。 不要重复标题。 现在我使用shutil如下。

import shutil
import time
csv_files = ['file1.csv', 'file2.csv', 'file3.csv', 'file4.csv', 'file5.csv', 'file6.csv']

target_file_name = 'target.csv';
start_time = time.time()
shutil.copy(csv_files[0], target_file_name)
with open(target_file_name, 'a') as out_file:
    for source_file in csv_files[1:]:
        with open(source_file, 'r') as in_file:
            in_file.readline()
            shutil.copyfileobj(in_file, out_file)
            in_file.close()
    out_file.close()
print("--- %s seconds ---" % (time.time() - start_time))

编辑

当我在终端中尝试time cat file[1-4].csv > BigBoy 命令时,我得到了以下输出。 0.08s user 4.57s system 60% cpu 7.644 total。 也就是说 cat 命令大约需要 4.5 秒,但 Python 程序需要 17.46 秒。我使用了 4 个 csv 文件,每个文件大小为 116MB。

我想知道,Python 中是否还有其他方法可以更有效地处理这些场景。 您可以从here 下载大型 csv 文件。

【问题讨论】:

  • 是的,高效。我编辑了我的帖子。谢谢
  • 我用 4 个 116MB 的 csv 文件尝试了代码 sn-p。耗时 17.46 秒。我想知道是否有任何其他库/方法可以更有效地处理文件操作。
  • 试试shell看看你的磁盘有多快time cat file[1-4].csv > BigBoy
  • 大约 4.5 秒 0.08s user 4.57s system 60% cpu 7.644 total
  • 我不会将其作为答案发布,因为您要求提供 Python 解决方案,但似乎完成工作的最快方法是启动子进程并运行以下命令以免重复标题awk '(FNR>1)||(NR==1)' file1.csv file2.csv file3.csv...

标签: python csv concatenation large-files


【解决方案1】:

为此,最好使用 csvkit 中的 csvstack。还有很多其他的东西可以从控制台处理 csv 文件。

csvstack file1.csv file2.csv ...

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 2022-01-16
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2018-11-08
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多