2017-12-24 3 views
0

디렉토리를 반복적으로 검색하고 문자열이 "AWSTemplateFormatVersion" 인 파일 만 표시하려고합니다.파이썬은 디렉토리를 반복적으로 검색하여 특정 문자열이 포함 된 파일 만 표시합니다.

import os, json 

cfn = [".json", ".template", ".yaml", ".yml"] 
dir = "./janitor" 

def cloudFormation(dir): 
    for root, dirs, files in os.walk(dir): 
     for file in files: 
      if file.endswith(tuple(cfn)): 
       with open(os.path.join(root, file), 'r') as fin: 
        data = fin.read() 
        print("************ Break **************") 
        print(data) 
        print(os.path.join(root, file)) 
    return data 

if __name__ == "__main__": 
    cloudFormation(dir) 
+2

''AWSTemplateFormatVersion "in data'? –

+0

왜'grep -R'을 사용하지 않는가? –

답변

1

어때? 마이크 뮐러 (Mike Muller)가 의견에서 제안한대로 data에 발생을 테스트합니다. 대신 마지막data 값을 인쇄하는 또한, 나는 진정한 조건을 모든 파일의 목록을 반환하도록 코드를 변경했습니다 :

import os, json 

cfn = [".json", ".template", ".yaml", ".yml"] 
dir = "./janitor" 

def cloudFormation(dir): 
    files_with_string = [] 
    for root, dirs, files in os.walk(dir): 
     for file in files: 
      if file.endswith(tuple(cfn)): 
       with open(os.path.join(root, file), 'r') as fin: 
        data = fin.read() 
        if "AWSTemplateFormatVersion" in data: 
         files_with_string.append(os.path.join(root, file)) 
         print("************ Break **************") 
         print(data) 
         print(os.path.join(root, file)) 
    return files_with_string 

if __name__ == "__main__": 
    cloudFormation(dir) 

나는 당신이 그것을 구현하는 방법을 모르는 당신의 해결책; 즉 파일의 수와 크기는 여기에 두 가지 메모가 있습니다.

파일이 크면 전체 파일을 읽는 대신 파일의 부분 만 점진적으로 읽으십시오.

파일이 많으면 모든 파일 이름 목록을 반환하는 대신 생성기 기능을 사용하는 것이 좋습니다.

관련 문제