How to save matches for items in a list in one file to another file

I came up with this code. And I do not get anything saved in the conclusion, He remains empty. Although the code works, and I see the correct print matches on the console.

for item in somelist:
    with open('eng.txt','r') as dic, open('output.txt', 'w') as output:
        for line in dic:
            if re.match(item, line):
                output.write(line)
                print line

I tried another version:

for item in somelist:
    with open('eng.txt','r') as dic:
        for line in dic:
            if re.match(item, line):
                with open('output.txt', 'w') as output:
                    output.write(line)
                    print line

Thus, it only saves the last line, but not all matches. How can i fix this?

+4
source share
1 answer

In this case, open the output file in the first step, and then just write to the file if you want.

with open('output.txt', 'w') as output:
    for item in final_list:
        with open('eng.txt','r') as dic:
            for line in dic:
                if re.match(item, line):
                    output.write(line)
                    print line

You created the output of a file object every time new in the second code fragment.

+4
source

Source: https://habr.com/ru/post/1612050/


All Articles