python读取文件夹中文件内容

#/usr/bin/python
# encoding: utf-8
'''
1、读取指定目录下的所有文件
2、读取文件,正则匹配出需要的内容,获取文件名
'''
import os.path
import re
 
 
# 遍历指定目录,显示目录下的所有文件名
def eachFile(filepath):
    pathDir =  os.listdir(filepath)#这一步就已经实现拿到文件夹下的文件名了
    for allDir in pathDir:
        child = os.path.join('%s\%s' % (filepath, allDir))
        if os.path.isfile(child):
            readFile(child)
            continue
        eachFile(child)
   
# 遍历出结果 返回文件的名字
def readFile(filenames):
        fopen = open(filenames, 'rb') # r 代表read
        fileread = fopen.read()
        fopen.close()
        t=re.search(b'1234',fileread)#进行匹配的内容为‘1234’
        if t:
#             print "匹配到的文件是:"+filenames
            arr.append(filenames)       
 
if __name__ == "__main__":
    filenames = 'D:\java\\answer\\Thinking in Java4 Answer' # refer root dir
    arr=[]
    eachFile(filenames)
    for i in arr:
        print i

猜你喜欢

转载自blog.csdn.net/qq_33485434/article/details/87877709