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:UsersDawn PhilipDocumentsdocuments")
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?"
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…