How to find and replace multiple lines in text file?

前端 未结 2 1350
闹比i
闹比i 2020-12-07 02:26

I am running Python 2.7.

I have three text files: data.txt, find.txt, and replace.txt. Now, find.txt contains se

2条回答
  •  广开言路
    2020-12-07 03:29

    If the file is large, you want to read and write one line at a time, so the whole thing isn't loaded into memory at once.

    # create a dict of find keys and replace values
    findlines = open('find.txt').read().split('\n')
    replacelines = open('replace.txt').read().split('\n')
    find_replace = dict(zip(findlines, replacelines))
    
    with open('data.txt') as data:
        with open('new_data.txt', 'w') as new_data:
            for line in data:
                for key in find_replace:
                    if key in line:
                        line = line.replace(key, find_replace[key])
                new_data.write(line)
    

    Edit: I changed the code to read().split('\n') instead of readliens() so \n isn't included in the find and replace strings

提交回复
热议问题