从第一个文件中搜索第二个文件,然后在python中输出到第三个文件

时间:2014-09-17 22:30:57

标签: python search

我想通过使用第一个文件作为输入并输出到第三个文件来搜索第二个文件中行的出现。它也必须快速列表第二个文件超过200k,第一个文件高于75k。

**FILE 1**
1234
2324
534
235
1
643

**FILE 2**

643, 30, , , People, email@example.com,.....
1234, 45, , , People, email@example.com,.....
643, 32, , , People, email@example.com,.....
4536, 654, , , People, email@example.com,.....
898, 354, , , People, email@example.com,.....

**FILE 3**
643, 30, , , People, email@example.com,.....
1234, 45, , , People, email@example.com,.....

那是伙计们。在此先感谢。

1 个答案:

答案 0 :(得分:0)

从第一个文件中读取ID,然后使用第二个文件的行检查起始编号是否在您收集的ID列表中。将匹配添加到列表并将列表写入第三个文件。

ids = []
with open('file1') as f:
    ids.extend(id.strip() for id in f)
matches = []
with open('file2') as f:
    for line in f:
        if line.split(',')[0] in ids:
            matches.append(line)
with open('file3', 'w') as f:
    for match in matches:
        f.write(match)
相关问题