dimanche 6 août 2017

Python print lines.append() in loop if/else

This is my problem, I have 2 files, where I want to read and print lines.append():

File1:

ID1 desc1

ID2 desc2

ID3 desc3

ID4 desc4

File 2:

ID1 random1

ID5 random5

ID06 random6

What I would like to get is:

ID1 random1 desc1

ID5 random5 desc5

ID6 randomI nothing

However, my current code:

address = {}

with open('address.txt', 'r') as f:
    rows = (line.rstrip().split('\t') for line in f)
    address = { row[0]:row[1:] for row in rows }

    for key, value in address.items():

        with open('families.txt', 'r') as f:    
            for line in f.readlines():
                line = line.rstrip('\n')
                line = line.split('\t')
                if line[0] == key: 
                    line.append(str(address[key]))
                    print ('\t'.join(line))
                else:
                    line.append('nothing')
                    print ('\t'.join(line))

However, I am getting a loop instead

ID1 random1 desc1

ID5 random5 nothing

ID6 randomI nothing

ID1 random1 nothing

ID5 random5 desc5

ID6 random6 nothing

Also, would be nice if someone suggests me the best way to discard the square brackets that are printed as part of the 'value' of my dictionary at the end.

Thank you so much

Aucun commentaire:

Enregistrer un commentaire