簡體   English   中英

Python 2.7 腳本 - 在目錄和子目錄中的所有文件中搜索字符串

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

我有一個名為文檔的文件夾,其中有 3,000 個文本文件和兩個子目錄:其中包含數千個文本文件。

我正在嘗試對其進行編碼,以便它搜索目錄和子目錄中的內容。

例如:我希望python腳本在所有文本文件中搜索字符串,如果找到,輸出路徑文本文件名和字符串。

我到目前為止得到的代碼是:

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

當我運行它時,它會向我顯示包含“x”的所有文本文件名稱,但我需要它在文本文件中搜索字符串並輸出包含該字符串的文件的路徑方式。

我的問題是“如何獲取代碼以在文本文件中搜索(字符串)內容並打印“找到的字符串 > 路徑 C:/X/Y/Z?”

至少對我來說 glob.glob() 只搜索了頂級目錄。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM