Python 3.x 嵌套用于循环csv文件

Python 3.x 嵌套用于循环csv文件,python-3.x,loops,csv,iterator,iterate,Python 3.x,Loops,Csv,Iterator,Iterate,我有来自同一来源的2.csv数据集。我试图检查第一个数据集中的任何项目是否仍存在于第二个数据集中 #!/usr/bin/python import csv import json import click @click.group() def cli(*args, **kwargs): """Command line tool to compare and generate a report of item that still persists from one report t

我有来自同一来源的2.csv数据集。我试图检查第一个数据集中的任何项目是否仍存在于第二个数据集中

#!/usr/bin/python

import csv
import json
import click

@click.group()

def cli(*args, **kwargs):
    """Command line tool to compare and generate a report of item that still persists from one report to the next."""
    pass

@click.command(help='Compare the keysets and return a list of keys old keys still active in new keyset.')
@click.option('--inone', '-i', default='keys.csv', help='specify the file of the old keyset')
@click.option('--intwo', '-i2', default='keys2.csv', help='Specify the file of the new keyset')
@click.option('--output', '-o', default='results.json', help='--output, -o,   Sets the name of the output.')
def compare(inone, intwo, output):

    csvfile = open(inone, 'r')
    csvfile2 = open(intwo, 'r')
    jsonfile = open(output, 'w')

    reader = csv.DictReader(csvfile)
    comparator = csv.DictReader(csvfile2)
    for line in comparator:
        for row in reader:
            if row == line:
                print('#', end='')
                json.dump(row, jsonfile)
                jsonfile.write('\n')
            print('|', end='')
        print('-', end='')


cli.add_command(compare)

if __name__ == '__main__':
    cli()
假设每个csv文件中有20个项目。它当前将迭代40次,并在我期望它迭代400次并创建剩余项的报告时结束


除了迭代之外,其他一切似乎都在工作。有没有人想到更好的方法

迭代40次听起来很正确-当您在
DictReader
中进行迭代时,您实际上是在对包装好的文件行进行迭代,一旦完成迭代,它就不会神奇地重置到开始处-迭代器就完成了

这意味着您的代码将开始迭代
比较器中的第一个项目
(1),然后迭代
读取器中的所有项目
(20),然后从
比较器中获取下一行
(1),然后在
读卡器
中,它将没有任何东西可以重复,因此它将转到下一个
比较器
行,依此类推,直到它在剩余的比较器行(18)上循环-总共产生40个循环

如果您真的想迭代所有行(内存不是问题),您可以将它们存储为列表,然后每当您在循环中为..启动
时,您就会得到一个新的迭代器,因此:

reader = list(csv.DictReader(csvfile))
comparator = list(csv.DictReader(csvfile2))
应该给你一个即时修复。或者,您可以使用
csvfile.seek(0)
在循环后重置
读卡器
“steam”

这就是说,如果您只想比较行,并且希望没有多少行会不同,那么您可以在csv.reader()中加载第一行以获取“header”,然后通过直接比较行来完全放弃
csv.DictReader
。然后,当发生更改时,您可以将该行弹出到
csv.reader()
中以正确解析它,然后将其映射到headers表以获取变量名称


在大型数据集上,这应该要快得多,再加上通过文件查找可以让您不必在内存中存储比当前I/O缓冲区更多的数据。

我的实际数据集一行是58k,另一行是580k。我想我的电脑上可能只有足够的内存,可以用第一种方式完成。然而,我的数据只会越来越大,所以请您详细说明第二种方法,我试图一次只将每个文件中的一行加载到内存中,但无法找到它。谢谢你的帮助!