简体   繁体   中英

Replace each line containing a specific word from the first file with the line from the second file

I have two txt files, the first one contains duplicated word "PACKAGES", i want to replace each "PACKAGES" word with a line from file 2

NEW FUSTAT TOURS
City
USA
Address
napolean
PACKAGES
Test TOURS
City
UK
Address
napolean
PACKAGES

Here's one way you could do it:

with open('file1.txt', encoding='utf-8') as f1:
    with open('file2.txt', encoding='utf-8') as f2:
        f2lines = iter(f2.readlines())
        for f1line in f1:
            if f1line.startswith('PACKAGES'):
                print(next(f2lines), end='')
            else:
                print(f1line, end='')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM