Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do a search-and-replace across all files in a folder through python?

I'd like to learn to use python as a command line scripting replacement. I spent some time with python in the past but it's been a while. This seems to be within the scope of it.

I have several files in a folder that I want to do a search-and-replace on, within all of them. I'd like to do it with a python script.

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

like image 485
fruit Avatar asked Jun 24 '10 13:06

fruit


People also ask

How do I find and replace in all files?

Choose Replace in files from the list of results. On the Edit menu, expand Find and Replace. Choose Replace in Files.

How do I search all files in a directory in Python?

To get a list of all the files and folders in a particular directory in the filesystem, use os. listdir() in legacy versions of Python or os. scandir() in Python 3.


1 Answers

Welcome to StackOverflow. Since you want to learn yourself (+1) I'll just give you a few pointers.

Check out os.walk() to get at all the files.

Then iterate over each line in the files (for line in currentfile: comes in handy here).

Now you need to know if you want a "stupid" replace (find/replace each foo even if it's in the middle of a word (say foobar - do you want foofoobar as a result?) or a smart replace.

For the former, look at str.replace(), for the latter, look at re.sub() and figure out what r'\bfoo\b' means.

like image 170
Tim Pietzcker Avatar answered Oct 25 '22 02:10

Tim Pietzcker