Python-第n行写入新文件

时间:2019-07-17 09:47:17

标签: python

我的订户列表很长。现在,我将它们全部写入一个csv文件。我想将它们拆分,以便每第1000行创建一个新文件并开始写入该文件,依此类推,直到完成。

当前代码:

with open(path, mode='w', newline='') as filename:
        writer = csv.writer(
            filename,
            delimiter=';',
            quotechar='"',
            quoting=csv.QUOTE_MINIMAL
        )

        writer.writerow(['email', 'name'])

        for subscriber in subscribers:
            writer.writerow([subscriber['Email'], subscriber['Name']])

如何扩展此功能以获得所需的功能?

1 个答案:

答案 0 :(得分:2)

您可以分块订户列表:

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i + n]

for subscribers_thousand in chunks(subscribers, 1000):
    # Remember to change path for each 1000 subscribers chunk
    with open(path, mode='w', newline='') as filename:
        writer = csv.writer(
            filename,
            delimiter=';',
            quotechar='"',
            quoting=csv.QUOTE_MINIMAL
        )
        for subscriber in subscribers_thousand:
            writer.writerow([subscriber['Email'], subscriber['Name']])

切记在每次迭代中更改文件名,以免覆盖文件。

注意:我从this topic in SO获得了这种块方法。就像魅力一样