python 遍历文件夹及文件

# -*- 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值