Script to find and replace strings in multiple text files
Here's a demonstration of how to use a Python script to find and replace one string with another in multiple text files. (Note that I'm working in version 3.7 of Python IDLE. )
In this example we're working with three text files that each refer to a New York city, which is misidentified as being in New Jersey.
Begin by importing the os module (which can enable operating system dependent functionality) and the re module for regular expression operations.
>>> import os, re
Set the directory in which you want to work:
>>> directory = os.listdir('C:/foofolder8')
Confirm the current directory: >>> os.chdir('C:/foofolder8')
Loop through each of the files in the folder: >>> for file in directory: open_file = open(file,'r') read_file = open_file.read()
With re.compile set the string you want to replace: regex = re.compile('jersey')
With regex.sub set the string you want to insert in: read_file = regex.sub('york', read_file)
Finally write in the new text: write_file = open(file, 'w') write_file.write(read_file)
The text files will be automatically updated.
Note that you may find an error in the last file.
Thanks to Abder Rahman-Ali for posting this script here.