Check the existence of a string in a file from another file

Asked

Viewed 40 times

-1

I have two files, one is this:

gp2,POL-AES-SHA1,Prop-AES-SHA1
gp2,POL-AES-SHA1-PFS-2,Prop-AES-SHA
POL-3DES-SHA,Prop-3DES-SHA

Note that you can have 2 or 3 items per line (separated by comma).

In the second file I have:

Prop-AES-SHA1,sha1,aes-256-cbc,8
Prop-AES-SHA,sha1,aes-128-cbc,24
POL-3DES-SHA,sha1,3des
IPSEC-AES-256-MD5,md5,aes-256-cbc
IPSEC-AES-256-CBC-SHA256,sha256,aes-256-cbc,8

Note that you can have 3 or 4 items per line, also separated by a comma.

The idea is that I take the last item of each line in the first file and look for it in the second file. If I find, I bring all the items from the row and create a row by mixing items from the two files.

It only analyzes 1 line and the code for:

file1 = open('file1')
file2 = open('file2')

for i in file1:
    i = i.strip().split(',')
    last_i = i[-1]
    for i2 in file2:
        if last_i in i2:
            print(f'{i} + {i2}')

1 answer

-1

From what I understand, you want to introduce everyone who gives 'match', but this second is only going through the file once. In this case, either you would store its contents in some corner, or you would have to scroll through it again every iteration of i.

This way should solve your problem.

file1 = open('file1.txt')

for i in file1:
    i = i.strip().split(',')
    last_i = i[-1]

    with open('file2.txt') as file2:
        for j in file2:
            if last_i in j:
                print(f'{i} + {j}')
  • I would like to thank you immensely for your help. Thank you for the tok on the opening of the second file. It worked, now I can adjust the print result and continue with the script! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.