比较两个文本文件和第三个文件中的输出

时间:2015-03-12 17:11:45

标签: python

我有两个文件与VRM列表和其他包含该名称的图像。

这是格式: 文本文件1:

A10KLG
M10SNW
N12TPC
P03GRI

TEXT FILE 2:DecathlonIN / 2015-03-12 /文件的结构;                                        SmythOUT / 2015年3月12日/

DecathlonIN / 2015-03-12 / - 这是在文本文件2中

今天的日期文件夹里面是这些图片。

    A10KLG-GBR_DecathlonIN_2015-03-12_10-52-33-152.jpg
    M10SNW-GBR_DecathlonIN_2015-03-12_11-58-35-162.jpg
    N12TPC-GBR_DecathlonIN_2015-03-12_14-51-33-152.jpg
    SKLG3-GBR_DecathlonIN_2015-03-12_10-52-33-152.jpg
    K10SNW-GBR_DecathlonIN_2015-03-12_10-52-33-152.jpg
    ST2TPC-GBR_DecathlonIN_2015-03-12_10-52-33-152.jpg

I need to find any any vrm which matches in the third file.

this is my code:

    FILE1 = "file1.txt"
    FILE2 = "file2.txt"
    OUTPUT = "file3.txt"

    with open(FILE1) as inf:
        match = set(line.strip() for line in inf)

    with open(FILE2) as inf, open(OUTPUT, "w") as outf:
        for line in inf:
            if line.split(' ', 1)[0] in match:
                outf.write(line)-----

就像A10KLG在两个文件中匹配一样,它应该在另一个文件中显示...

A10KLG-GBR_DecathlonIN_2015-03-12_10-52-33-152.jpg

1 个答案:

答案 0 :(得分:0)

在所有数据之间进行最简单的拆分:-

FILE1 = "file1.txt"
FILE2 = "file2.txt"
OUTPUT = "file3.txt"

with open(FILE1) as inf:
    match = set(line.strip() for line in inf)

with open(FILE2) as inf, open(OUTPUT, "w") as outf:
    for line in inf:
        if line.split('-')[0] in match:
            outf.write(line)

file3.txt

  

A10KLG-GBR_DecathlonIN_2015-03-12_10-52-33-152.jpg
  M10SNW-GBR_DecathlonIN_2015-03-12_11-58-35-162.jpg
  N12TPC-GBR_DecathlonIN_2015-03-12_14-51-33-152.jpg