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
".
Choose Replace in files from the list of results. On the Edit menu, expand Find and Replace. Choose Replace in Files.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With