python 查找指定內容的txt文件


程序設計思路:1. 利用os.walk()找出所有的文件;2.利用正則找到指定后綴的文件;3.找到需要的txt文件后,通過open().readlines()讀取文件中每行數據;4.讀取后,保存正則匹配到數據的文件;5.你懂的。
#!/usr/bin/env python
#coding:utf8

import os
import re

regtxt = r'.+?\.txt' #掃描對象為txt文件.
regcontent = r'what is your name' #列出內容含有'what is your name'的文件

class FileException(Exception):
    pass

def getdirlist(filepath):
    """獲取目錄下所有的文件."""

    txtlist = [] #文件集合.
    txtre = re.compile(regtxt)
    needfile = [] #存放結果.
    for parent, listdir, listfile in os.walk(filepath):
        for files in listfile:
            #獲取所有文件.
            istxt = re.findall(txtre, files)
            filecontext = os.path.join(parent, files)
            #獲取非空的文件.
            if istxt :
                txtlist.append(filecontext)
                #將所有的數據存放到needfile中.
                needfile.append(readfile(filecontext)) 

    if needfile == []:
        raise FileException("no file can be find!")
    else:
        validatedata = getvalidata(needfile)
        print validatedata
        print 'total file %s , validate file %s.' %(len(txtlist),len(validatedata))

def getvalidata(filelist=[]):
    """過濾集合中空的元素."""

    valifile = []
    for fp in filelist:
        if fp != None:
            valifile.append(fp)
    return valifile

def readfile(filepath):
    """通過正則匹配文本中內容,並返回文本."""

    flag = False
    contentre = re.compile(regcontent)
    fp = open(filepath, 'a+')
    lines = fp.readlines()
    flines = len(lines)
    #逐行匹配數據.
    for i in range(flines): 
        iscontent = re.findall(contentre, lines[i]) 
        if iscontent:
            fp.close()
            return filepath

if __name__ == "__main__":
    getdirlist('C:\python27')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM