1. 程式人生 > >Python 資料夾遍歷和檔案查詢

Python 資料夾遍歷和檔案查詢

# -*- coding: utf-8 -*-
#to find where use the table on xxxxx xxxxxx   production env

'''
在專案中我們元資料管理的不是很好,如果先知道一張表在哪裡用過,就需要寫個程式去遍歷下
'''

import os
import os.path
rootdir =   "C:\\Users\\IBM_ADMIN\\IBM\\rationalsdp\\workspace"#     # 指明被遍歷的資料夾
query = "xxxxxxxxx"                           
def walk_all_files(rootdir,query):
    for parent,dirnames,filenames in os.walk(rootdir):   #for迴圈自動完成遞迴列舉  #三個引數:分別返回1.父目錄(當前路徑) 2.所有資料夾名字(不含路徑) 3.所有檔名字
        for dirname in dirnames:                         #輸出資料夾資訊
            #print "parent is:" + parent
            #print "dirname is :" + dirname
            pass

        for filename in filenames:                       #輸出檔案資訊
            #print "parent is :" + parent
            #print "filename is:" + filename
            #print "the full name of the file is :" + os.path.join(parent,filename)
            is_file_contain_word(os.path.join(parent,filename),query)
def is_file_contain_word(file_,query_word):
    #print 1111111
    if query_word in open(file_).read() :
        print file_
        filecontext = open(file_).read()
        lines = filecontext.split('\n')                 # python列印關鍵詞所在行
        for line in lines:
            if query_word in line:
                print line




walk_all_files(rootdir,query)
print "done"


'''
http://www.iplaypy.com/jichu/note.html
please explain os.walk() :
walk()方法語法格式如下:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
引數
    top -- 根目錄下的每一個資料夾(包含它自己), 產生3-元組 (dirpath, dirnames, filenames)【資料夾路徑, 資料夾名字, 檔名】。
    topdown --可選,為True或者沒有指定, 一個目錄的的3-元組將比它的任何子資料夾的3-元組先產生 (目錄自上而下)。如果topdown為 False, 一個目錄的3-元組將比它的任何子資料夾的3-元組後產生 (目錄自下而上)。
    onerror -- 可選,是一個函式; 它呼叫時有一個引數, 一個OSError例項。報告這錯誤後,繼續walk,或者丟擲exception終止walk。
    followlinks -- 設定為 true,則通過軟連結訪問目錄。

返回值

該方法沒有返回值。

'''