2017-11-21 3 views
0

나는 3000 개의 텍스트 파일과 두 개의 하위 디렉토리가있는 document라는 폴더가 있습니다. 여기에는 더 많은 수천 개의 텍스트 파일이 있습니다.Python 2.7 Script - 디렉토리 및 하위 디렉토리의 모든 파일에서 문자열 검색

디렉토리와 하위 디렉토리의 내용을 검색하도록 코드를 작성하려고합니다.

예 : 파이썬 스크립트가 모든 텍스트 파일에서 문자열을 검색하고 찾으면 문자열과 함께 경로 텍스트 파일 이름을 출력합니다.

내가 지금까지 가지고 코드입니다 : 내가 이것을 실행하면 나에게 'x'를 포함하는 모든 텍스트 파일의 이름을 표시하지만 나는 그것이 텍스트 파일 내의 문자열을 검색 할 필요가

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 

문자열이 들어있는 파일의 경로를 출력 할 수 있습니다.

내 질문은 '텍스트 파일 내에서 (문자열) 내용을 검색하고 "문자열을 찾을 수 있음> 경로 C :/X/Y/Z?"라는 코드를 얻는 방법입니다. "

답변

0

적어도 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 
관련 문제