top of page

Python script to search multiple text files

A very useful script has been posted here, which can be used to search for a string in multiple text files. Simply copy the below code into a text file and save it with the extension '.py'. (Note that I have added this code:

k=input("press close to exit")

. . . at the end to prevent the window from closing after the script is run.)

k=input("press close to exit")

Double-click on the new file and it will prompt you to enter the path containing the text files you are searching through; the extension of the text files; and the string to be searched for.

The results return each line in the file in which the string appears.

#Import os module import os

# Ask the user to enter string to search search_path = input("Enter directory path to search : ") file_type = input("File Type : ") search_str = input("Enter the search string : ")

# Append a directory separator if not already present if not (search_path.endswith("/") or search_path.endswith("\\") ): search_path = search_path + "/" # If path does not exist, set search path to current directory if not os.path.exists(search_path): search_path ="."

# Repeat for each file in the directory for fname in os.listdir(path=search_path):

# Apply file type filter if fname.endswith(file_type):

# Open file for reading fo = open(search_path + fname)

# Read the first line from the file line = fo.readline()

# Initialize counter for line number line_no = 1

# Loop until EOF while line != '' : # Search for string in line index = line.find(search_str) if ( index != -1) : print(fname, "[", line_no, ",", index, "] ", line, sep="")

# Read next line line = fo.readline()

# Increment line counter line_no += 1 # Close the files fo.close() k=input("press close to exit")

bottom of page