标签:
1、os模块
1.1 Python os.walk的用法与举例
os.walk(top, topdown=True, onerror=None, followlinks=False)
可以得到一个三元tupple(dirpath, dirnames, filenames),
第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
dirpath 是一个string,代表目录的路径,
dirnames 是一个list,包含了dirpath下所有子目录的名字。
filenames 是一个list,包含了非目录文件的名字。
这些名字不包含路径信息,如果需要得到全路径,需要使用os.path.join(dirpath, name).
通过for循环即可完成目录的递归
[root@saltstack ~]# cat os_walk.py import os filedir=‘./sadoc‘ def ccc(): for root,dirs,files in os.walk(filedir): for dir in dirs: print(os.path.join(root,dir)) for file in files: print(os.path.join(root,file)) # os.system("pause") if __name__ == ‘__main__‘: ccc() [root@saltstack ~]# python os_walk.py ./sadoc/.svn ./sadoc/tags ./sadoc/branch ./sadoc/trunk ./sadoc/.svn/text-base ./sadoc/.svn/tmp ./sadoc/.svn/prop-base ./sadoc/.svn/props ./sadoc/.svn/entries ./sadoc/.svn/tmp/text-base ./sadoc/.svn/tmp/prop-base ./sadoc/.svn/tmp/props ./sadoc/tags/.svn ./sadoc/tags/.svn/text-base ./sadoc/tags/.svn/tmp ./sadoc/tags/.svn/prop-base ./sadoc/tags/.svn/props ./sadoc/tags/.svn/entries ./sadoc/tags/.svn/tmp/text-base ./sadoc/tags/.svn/tmp/prop-base ./sadoc/tags/.svn/tmp/props ./sadoc/branch/.svn ./sadoc/branch/.svn/text-base ./sadoc/branch/.svn/tmp ./sadoc/branch/.svn/prop-base ./sadoc/branch/.svn/props ./sadoc/branch/.svn/entries ./sadoc/branch/.svn/tmp/text-base ./sadoc/branch/.svn/tmp/prop-base ./sadoc/branch/.svn/tmp/props ./sadoc/trunk/.svn ./sadoc/trunk/.svn/text-base ./sadoc/trunk/.svn/tmp ./sadoc/trunk/.svn/prop-base ./sadoc/trunk/.svn/props ./sadoc/trunk/.svn/entries ./sadoc/trunk/.svn/tmp/text-base ./sadoc/trunk/.svn/tmp/prop-base ./sadoc/trunk/.svn/tmp/props
应用场景:
1)遍历目录下所有文件替换文件内容
2)目录下文件批量重命名
标签:
原文地址:http://www.cnblogs.com/madsnotes/p/5491400.html