Search code examples
pythonfilecomparison

Python: Specific search and output new item results in new file


I'm trying to learn python :) and sorry if it is a really noob question. I tried to search but couldn't find exactly what i was looking for.

I'm trying to compare 2 files. but not just straight foward like this. I want something more precise

there will be more then 200 name entry and i need to extract new entries from file 2

let say file one has those entry:

some random text -Name: Item_01_01- some random text
some random text -Name: Thing_01_01- some random text

and file 2 has
some random text -Name: Item_01- some random text
some random text -Name: Thing_01- some random text
some random text -Name: Object_02- some random text

I want to do something that will compare the 2 files and extract the new item in file 2

so i want the info Object_02 appear in my output file

searching the info into -Name: XXXXX-

I know how to read file and write files in python, it the info i'm not sure how to get it.

And yes file 1 has more number at then ends of each items

I hope it's clear

(sorry English not my main language)

Thanks a lot in advance for help.


Solution

  • here is the final working result of my code. I had to adjust it to make sure that my file2 don't get that extra weird space that I was not awarded of. I did some custom adjustment so it work nicely with my needs.

    instead if using name i used ID that are 16 digit numbers.

    Thanks to @davedwards for precious help

    the code:

    with open('file1.txt', 'r') as f:
        f1_data = f.readlines()
    with open('file2.txt', 'r') as f:
        f2_data = f.readlines()
    f2_data = f2_data[0].split(" ")
    new_data = []
    for terms in f2_data:
        found = False
        for line in f1_data:
            if line.find(terms) != -1:
                found = True
                break
        if not found:
            new_data.append(terms)
    with open('new_data.txt', 'w') as f:
        f.writelines(" OR ".join(new_data))