Madsen
Madsen

Reputation: 25

Python iterate and write to second file

I am trying to iterate through a tab delimited text file and write rows that contain a certain value to a second text file. My attempt is below. Calling print(line) on the original file after line three prints the correct rows, and I get the same issue 151 message (shown below) when I use open & close instead of with so I'm assuming the problem relates to the way I've used file.write(line). I'm pretty new at this...

with open("file_1.idx", "r") as file_1:
    for line in file_1:
        if "abc" in line:
            with open("file_2.rtf", "w") as file_2:
                file_2.write(line)


151
151
151

Upvotes: 1

Views: 71

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46859

you reopen (and overwrite) the second file. this should work:

with open("file_1.idx", "r") as file_1, open("file_2.rtf", "w") as file_2:
    for line in file_1:
        if "abc" in line:
            file_2.write(line)

Upvotes: 1

Related Questions