top of page

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.


 

Sean O'Shea has more than 20 years of experience in the litigation support field with major law firms in New York and San Francisco.   He is an ACEDS Certified eDiscovery Specialist and a Relativity Certified Administrator.

​

The views expressed in this blog are those of the owner and do not reflect the views or opinions of the owner’s employer.

​

If you have a question or comment about this blog, please make a submission using the form to the right. 

Your details were sent successfully!

© 2015 by Sean O'Shea . Proudly created with Wix.com

bottom of page