Search and replace all files in a folder through python?

I would like to learn how to use python as a replacement for command line scripts. I spent some time with python in the past, but it was a while. This seems to fall within its scope.

I have several files in the folder in which I want to search and replace, in all of them. I would like to do this with a python script.

For example, search and replace all instances of " foo" with " foobar".

+5
source share
4 answers

Welcome to StackOverflow. Since you want to recognize yourself (+1), I will just give you some pointers.

os.walk(), .

(for line in currentfile: ).

, "" (/ foo, ( foobar - foofoobar)? .

str.replace(), re.sub() , r'\bfoo\b'.

+5

perl -pi -e 's/foo/foobar/' , Python:

import os
import re
_replace_re = re.compile("foo")
for dirpath, dirnames, filenames in os.walk("directory/"):
    for file in filenames:
        file = os.path.join(dirpath, file)
        tempfile = file + ".temp"
        with open(tempfile, "w") as target:
            with open(file) as source:
                for line in source:
                    line = _replace_re.sub("foobar", line)
                    target.write(line)
        os.rename(tempfile, file)

Windows, os.remove(file) os.rename(tempfile, file).

+2

, , , , , , .

import fileinput, sys, os

def replaceAll(file, findexp, replaceexp):
    for line in fileinput.input(file, inplace=1):
        if findexp in line:
            line = line.replace(findexp, replaceexp)
        sys.stdout.write(line)

if __name__ == '__main__':
    files = os.listdir("c:/testing/")
    for file in files:
        newfile = os.path.join("C:/testing/", file)
        replaceAll(newfile, "black", "white")

.

+1

This is an alternative since you have various Python solutions presented to you. The most useful utility (for me) on Unix / Windows is the GNU search command and replacement tools like sed / awk. to search for files (recursively) and replace, a simple command like this does the trick (the syntax comes from memory and is not tested). this says that find all the text files and change the word "old" to "new" in their contents, at the same time use sedto backup the source files ...

$ find /path -type f -iname "*.txt" -exec sed -i.bak 's/old/new/g' "{}" +;
0
source

All Articles