python-3.x 检查列中的值是否存在于另一个文件中,并打印其他文件中的行

7uhlpewt  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(159)

使用Python,如何使用Python csv检查列中的值是否存在于另一个文件中?
例如,我有两个文件:
文件1:

"time",text,"number","name"
"15:08:31.758","lorem dolor ipsum",6475,"Account1"
"15:08:31.748","lorem ipsum

dolor ",5145,"Account2"
"15:56:41.634","dolor ipsum lorem",4162,"Account3"

文件二:

"time",text,"number"
"15:48:34.865",YES,5145
"15:46:08.347",Yes,5142
"15:39:04.391",Yes,5146
"15:37:48.270",YES,4389
"15:36:37.476",Yes,5149
"15:30:23.950",YES,4166
"15:17:27.071",Yes,4388
"15:17:02.016",Yes,5144
"15:09:01.167",yes,2045

我想从文件1中搜索数字列中的每个值(6475、5145和4162),如果文件2中的数字字段中存在该值,则打印文件2中的整行。输出如下所示:

"15:48:34.865",YES,5145
mrphzbgm

mrphzbgm1#

使用csv模块,您可以轻松地读取和解析CSV文件,并比较每个文件的编号列中的值以查找匹配项
例如,我们读取并打开File1.csv文件,然后读取并打开DictReaderFile2.csv文件,然后检查每行中的数字值是否在从File1.csv提取的值集中

import csv

with open('File1.csv', newline='') as f1:
    reader1 = csv.DictReader(f1)
    numbers1 = set(row['number'] for row in reader1)

with open('File2.csv', newline='') as f2:
    reader2 = csv.DictReader(f2)
    for row in reader2:
        if row['number'] in numbers1:
            print(row)

相关问题