dizzle
dizzle

Reputation: 153

Python: Read line from File, check if in other file, if it is print line to output file

I have a text file with list of IDs. I want to iterate through the lines of that file, checking if the IDs appear in the lines of a second file, "extra_lines.txt". If the ID is present in a line of the second file, I want to print that whole line to output.txt. However, only the line containing the final ID is being printed. What am i doing wrong?

outfile = open("output.txt", "a")

def checkLine(ID):        
    with open("extra_lines.txt") as f:
        for line in f:
            if ID in line:
                outfile.write(line)

for ID in open("IDs.txt", "r"):
    checkLine(ID)      

Upvotes: 2

Views: 142

Answers (1)

Tom Rees
Tom Rees

Reputation: 455

My guess is that your 'ID' string contains a newline character for each line except the last. The result is that

if ID in line:

is failing, because 'line' doesn't contain the ID followed by a newline.

See Reading a file without newlines for how to read each line without the newline character.

ID.strip("\n")

works for me (Python 3.5).

Upvotes: 1

Related Questions