I have a folder named documents, within that I have 3,000 text files and two sub directories: which contains more thousands of text files.
I'm trying to code it so that it searches through the content within the directories and sub directories.
For example: I want the python script to search for string inside all the text files, and if found, output the the path text file name along with the string.
The code I got so far is:
import os
import glob
os.chdir("C:\Users\Dawn Philip\Documents\documents")
for files in glob.glob( "*.txt" ):
f = open( files, 'r' )
file_contents = f.read()
if "x" in file_contents:
print f.name
When I run this, it shows me the all the text files names that contains "x" but I need it search for the string inside the text file and to output the path way of the file which contains the string.
My question is that 'How do I get the code to search for the (string) content within the text files and print "String Found > Path C:/X/Y/Z?"
At least for me glob.glob() only searched through the top level directory.
import os
import glob
# Sets the main directory
main_path = "C:\\Users\\Dawn Philip\\Documents\\documents"
# Gets a list of everything in the main directory including folders
main_directory = os.listdir(main_path)
# This list will hold all of the folders to search through, including the main folder
sub_directories = []
# Adds the main folder to to the list of folders
sub_directories.append(main_path)
# Loops through everthing in the main folder, searching for sub folders
for item in main_directory:
# Creates the full path to each item)
item_path = os.path.join(main_path, item)
# Checks each item to see if it is a directory
if os.path.isdir(item_path) == True:
# If it is a folder it is added to the list
sub_directories.append(item_path)
for directory in sub_directories:
for files in glob.glob(os.path.join(directory,"*.txt")):
f = open( files, 'r' )
file_contents = f.read()
if "x" in file_contents:
print f.name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.