Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

Python 2.7 Script - Searching for a String in all files in Directories and Sub-Directories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...