# -*- coding: cp936 -*-
import os
import os.path
import ConfigParser
rootdir = r"D:\Project" # 指明被遍历的文件夹
PathList=list()
PathList_update=list()
PathDict=dict()
PathList_dict=dict()
cf = ConfigParser.ConfigParser()
##取得路径
for parent,dirnames,filenames in os.walk(rootdir): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
for filename in filenames: #输出文件信息
path=os.path.join(parent,filename)
PathList.append(path)
PathList_update = [PathList[i] for i in range(0, len(PathList) - 1) if ( ('project.cfg.ini') in PathList[i])]
## getSecs
def getSecs(path):
cf.read(path)
secs = cf.sections()
for x in secs:
kvs=cf.items(x)
PathList_dict[x]=kvs
PathDict[path]=PathList_dict
//不断遍历得到本目录下所有文件中的内容
for Path in PathList_update:
getSecs(Path)
for path in PathDict:
print path,' ==================================='
print ' '
print ' '
for x in PathDict[path]:
print x,":",PathDict[path][x]
print ' '
python遍历文件夹及文件,且读取目录下所有的文件内容。调用python自己集成的ConfigParser模块,很好用。
import ConfigParser
import os
import os.path
cf=ConfigParser.ConfigParser()
for parent,dirname,filenames in os.walk(rootdir):
for filename in filenames:
path=os.path.join(parent,filename)
cd.read(path)//调用ConfigParser的read()方法
secs=cf.sections()//获取文件中的section[]
kvs=cf.items(" ")//获取items