How to find and replace multiple lines in text file?

前端 未结 2 1347
闹比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:17

    couple things here:

    replace is not deprecated, see this discussion for details: Python 2.7: replace method of string object deprecated

    If you are worried about reading data.txt in to memory all at once, you should be able to just iterate over data.txt one line at a time

    data = open("data.txt", 'r')
    for line in data:
        # fix the line
    

    so all that's left is coming up with a whole bunch of find/replace pairs and fixing each line. Check out the zip function for a handy way to do that

    find = open("find.txt", 'r').readlines()
    replace = open("replace.txt", 'r').readlines()
    new_data = open("new_data.txt", 'w')
    for find_token, replace_token in zip(find, replace):
        new_line = line.replace(find_token, replace_token)
        new_data.write(new_line + os.linesep)
    

提交回复
热议问题