【问题标题】:Too many open output files while splitting a CSV拆分 CSV 时打开的输出文件过多
【发布时间】:2019-07-10 18:22:56
【问题描述】:

这里是python的新手尝试。

我尝试实现类似问题Splitting csv file based on a particular column using Python中讨论的内容

我的目标是获取一个包含 1500 万行 500 个股票代码的文件,并将每个股票代码放在自己的文件中。

但是,当我运行它时,我得到了

OSError: [Errno 24] 打开的文件太多:'APH.csv'

所有数据行都是按顺序排列的(即代码“A”的所有数据行都是一个接一个,所以我可以在继续下一个文件之前关闭一个文件)。我不确定在继续下一个之前我会在这段代码中的哪个位置关闭文件。仅供参考 - 如果重要的话,这是在 Mac 上。

我的代码是

import csv

with open('WIKI_PRICES_big.csv') as fin:    
    csvin = csv.DictReader(fin)
    # Category -> open file lookup
    outputs = {}
    for row in csvin:
        cat = row['ticker']
        # Open a new file and write the header
        if cat not in outputs:
            fout = open('{}.csv'.format(cat), 'w')
            dw = csv.DictWriter(fout, fieldnames=csvin.fieldnames)
            dw.writeheader()
            outputs[cat] = fout, dw
        # Always write the row
        outputs[cat][1].writerow(row)
    # Close all the files
    for fout, _ in outputs.values():
        fout.close()

【问题讨论】:

  • 你愿意使用 Pandas 吗?

标签: python python-3.x


【解决方案1】:

根据您描述的文件结构,以下应该这样做。

诀窍在于,如果代码值始终按顺序排列,则您只需随时打开单个文件输出文件。然后,您可以在遇到新的代码值时关闭旧的并重新打开新的。

import csv

fout = False
with open('WIKI_PRICES_big.csv') as fin:    
    csvin = csv.DictReader(fin)
    seen = []

    for row in csvin:
        cat = row['ticker']

        # Open a new file and write the header.
        if cat not in seen:
            seen.append(cat)

            if fout:  # Close old file if we have one.
                fout.close()

            fout = open('{}.csv'.format(cat), 'w')
            dw = csv.DictWriter(fout, fieldnames=csvin.fieldnames)
            dw.writeheader()

        # Always write the row
        dw.writerow(row)

    fout.close()

【讨论】:

  • 这仍然给出了太多打开的文件。明天我将采取不同的方法...谢谢
  • @Mary 你确定你复制并正确运行了这段代码吗?我在这里(也在 Mac 上)测试了最多 10,000 个输出文件,没有问题。
猜你喜欢
  • 1970-01-01
  • 2021-11-29
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多