python

python中如何读入文件夹数据

摘星
328
2021-05-26 18:58:34
栏目: 编程语言

python中读入文件夹数据的方法:1、导入os.path和re模块;2、获取文件夹中所有数据;3、通过正则表达式匹配相关的文件并打开读入即可。

python中如何读入文件夹数据

实例分析:

1、首先需要将os.path和re模块导入。

import os.path

import re

2、读入文件夹内的所有文件。

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)

# print child.decode('gbk') # .decode('gbk')是解决中文显示乱码问题

continue

eachFile(child)

3、通过正则表达式匹配相关的文件,获取文件名并打开读入即可。

def readFile(filenames):

fopen = open(filenames, 'r') # r 代表read

fileread = fopen.read()

fopen.close()

t=re.search(r'clearSpitValve',fileread)

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

0
看了该问题的人还看了