[python]怎么样用Python读取一个目录树-os.walk入门
来源:互联网 发布:数据与信息的关系是 编辑:程序博客网 时间:2024/05/29 18:51
原文: http://pythoncentral.org/how-to-traverse-a-directory-tree-in-python-guide-to-os-walk/
当你使用如Python这样一门编辑脚本语言的时候,你会发现自己经常会做一件事情,就是浏览文件目录结构和处理文件。然而有很多方法去做这件事情,Pyhton内建函数让这件事情变得轻而易举。
基本的目录遍历:
这里有个遍历目录的简单例子,打印出每个目录所包含的文件:
# Import the os module, for the os.walk functionimport os # Set the directory you want to start fromrootDir = '.'for dirName, subdirList, fileList in os.walk(rootDir): print('Found directory: %s' % dirName) for fname in fileList: print('\t%s' % fname)
os.walk 关注这些细节,每次循环都会得到3样东西:
dirName: 找到下一个目录
subdirList: 当前目录的所有子目录
fileList: 当前目录下的所有文件
我们将会得到向下面似的目录:
+--- test.py|+--- [subdir1]| || +--- file1a.txt| +--- file1b.png|+--- [subdir2]|+--- file2a.jpeg+--- file2b.html
上面这些代码的输出如下:
Found directory: . file2a.jpeg file2b.html test.pyFound directory: ./subdir1 file1a.txt file1b.pngFound directory: ./subdir2
改变下读取目录树的方式:
默认的,Python会自上而下的顺序遍历目录树,然后才会进入下面任意一个子目录。我们可 以从上面的输出看出来,当前的(.)目录打印完了,才会打印2个子目录。如果我们像要倒过来这个顺序就可以在os.walk加一个 topdown 参数:
import os rootDir = '.'for dirName, subdirList, fileList in os.walk(rootDir, topdown=False): print('Found directory: %s' % dirName) for fname in fileList: print('\t%s' % fname)
输出:
Found directory: ./subdir1 file1a.txt file1b.pngFound directory: ./subdir2Found directory: . file2a.jpeg file2b.html test.py
现在我们先看到子目录的文件,然后才向上到上一级目录。
有选择的读取目录:
到现在为止的例子都是简单的读取全部的目录,但是os.walk也可以让我们跳过目录树的某些部分。os.walk返回的每个目录,都提供了起子目录的列表,如果我们修改这个列表,就能控制它向下 读取的子目录,让我们改变下上面的例子足以让程序跳过某些目录。
import os rootDir = '.'for dirName, subdirList, fileList in os.walk(rootDir): print('Found directory: %s' % dirName) for fname in fileList: print('\t%s' % fname) # Remove the first entry in the list of sub-directories # if there are any sub-directories present if len(subdirList) > 0: del subdirList[0]
Found directory: .
file2a.jpeg
file2b.html
test
.py
Found directory: .
/subdir2
我们可以看到 子目录subdir1 被跳过了。
本文出自 “orangleliu笔记本” 博客,请务必保留此出处http://blog.csdn.net/orangleliu/article/details/8734555
- [python]怎么样用Python读取一个目录树-os.walk入门
- python os.walk 目录树
- Python读取文件目录树——os.walk
- Python 用 os.walk 遍历目录
- Python 用 os.walk 遍历目录
- Python 用 os.walk 遍历目录
- Python os.walk 遍历目录
- 【Python】目录路径之os.walk & os.path.walk
- python--内建os.walk遍历目录
- Python中用os.walk 遍历目录
- python os.walk
- python os walk笔记
- Python os.walk
- Python os.walk() 方法
- Python os.walk()
- Python os.walk() 简介
- Python os.walk 函数
- Python 之os.walk()
- C#知识复习之linq(一)
- 关于JEECG 开源声明
- AutoCompleteTextView和MultiAutoCompleteTextView的区别
- 对编程很有用的自然效应
- 我的Android进阶之旅------>Android项目目录结构分析
- [python]怎么样用Python读取一个目录树-os.walk入门
- [service] service生命周期,启动方式,与intentService的比较
- 为Editplus安装smali代码语法高亮插件
- 我的Android进阶之旅------>QR的生成(二维码)
- mem_fun & mem_fun_ref
- 01、考虑用静态工厂方法代替构造器
- Search in Rotated Sorted Array
- list_entry
- 转:Java语言的XPath API