John John - 9 months ago 29
Python Question

How to replace multiple strings in multiple text files?

SO! I am fairly new to Python and I have a large series of files that I need to replace certain lines with other lines.

I know this may be a little confusing, but let me explain.

So I have a directory full of files, let's so temp/.

I need to iterate through all the files in that directory, using Python and modify each file, replacing certain lines.

For this, I want to have one file called newStrings.txt

ReplaceWithThis
iLikeReplacingStuff


And I want these strings to replace lines from oldStrings.txt

I hate this string
Please get rid of me

Answer Source

Code has been tailored per the poster's request.

import os

folderLocation = "temp/"

lookup = dict()

with open("newString.txt","r") as values:
    with open("oldString.txt","r") as keys:
        keyLines = keys.readlines()
        valueLines = values.readlines()
        for i, line in enumerate(keyLines):
            lookup[line] = valueLines[i]


for subdir, dirs, files in os.walk(folderLocation):
    for fileIn in files:
        os.rename(folderLocation + fileIn, folderLocation + "old_" + fileIn)
        with open (folderLocation + "old_" + fileIn, "r") as fi:
            with open(folderLocation + fileIn, "w") as fo:
                for line in fi:
                    if line in lookup:
                        fo.write(lookup[line])
                    else:
                        fo.write(line)