Here we search a Python script file (or other text file) for one certain string, and copy any files containing this string to another folder.
Search File for Text and Copy
# copy Python files containing a given string
# from source folder to destination folder
# tested with Python24 by HAB
import os
import shutil
# supply your own folders, they have to exist!
source_folder = r"C:\Python24\Atest"
destination_folder = r"C:\Temp"
# select only Python .py files
extension = ".py"
# pick a string to search for (might be this file)
findstr = "source_folder"
for filename in os.listdir(source_folder):
source_file = os.path.join(source_folder, filename)
# prevent attempt to open subfolders, gives IOError
if source_file.endswith(extension):
if findstr in open(source_file).read():
dest_file = os.path.join(destination_folder, filename)
print "copied %s to %s" % (source_file, dest_file)
shutil.copyfile(source_file, dest_file)
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.