Python 使用 OS 模块实现目录遍历

我的目录结构

Python 使用 OS 模块实现目录遍历_python
也就是说我将要遍历的目录为: ​​​C:\\Users\\Eric\\Documents\\Pathon\\test​

方法

  1. 函数的迭代
  2. 使用 os.walk() 方法

方法1: 函数的迭代

此处主要是想记录下一个知识点 — 即使用 函数默认值 实现 静态变量

完整代码

# _*_ coding: utf-8 _*_
import os

# 使用 函数默认值 实现 静态变量
''' function: dirlist
arguments: path -- 文件路径
allfiles -- 默认值, 记录目录的结构
output: allfiles -- 返回目录结构, 以列表的形式'''
def dirlist(path, allfiles=[]):
# 列出 path 下的所有文件
filelist = os.listdir(path)
for filename in filelist:
# 将文件名和路径 path 连接在一起, 比如文件中有一个文件夹是 f1, 那么 filecompletepath
# 的结果是 C:\\Users\\Eric\\Documents\\Pathon\\test\\f1
filecompletepath = os.path.join(path, filename)
allfiles.append(filecompletepath)
# 判断 filecompletepath 是否是一个文件夹, 是的话再继续遍历
if os.path.isdir(filecompletepath):
dirlist(filecompletepath)
return allfiles

allfiles = dirlist('C:\\Users\\Eric\\Documents\\Python\\test')

for path in allfiles:
print path

输出结果

C:\Users\Eric\Documents\Python\test\f1
C:\Users\Eric\Documents\Python\test\f2
C:\Users\Eric\Documents\Python\test\f3
C:\Users\Eric\Documents\Python\test\jpg
C:\Users\Eric\Documents\Python\test\jpg\a
C:\Users\Eric\Documents\Python\test\jpg\getjpg.py

方法1 总结

开始我的代码是这样:

# diff 1: 少了默认参数 allfiles=[]
def dirlist(path):
filelist = os.listdir(path)
# 将 allfiles = [] 放在这里
allfiles=[]
for filename in filelist:
filecompletepath = os.path.join(path, filename)
allfiles.append(filecompletepath)
if os.path.isdir(filecompletepath):
dirlist(filecompletepath)
return allfiles

最后的结果是:

C:\Users\Eric\Documents\Python\test\f1
C:\Users\Eric\Documents\Python\test\f2
C:\Users\Eric\Documents\Python\test\f3
C:\Users\Eric\Documents\Python\test\jpg

** 得到这样的结果是因为: 当迭代函数 ​​dirlist​​​ 的时候, ​​allfiles = []​​​ 也会被执行,
所以最后某些路径不会被显示出来. 因此在这个时候突然想到, 应该用一个静态变量来实现自己
想要的效果 — 即每一次迭代不会将以前的结果消除, 可是 Pathon 并没有静态变量, 但是能用
函数的默认参数实现静态变量的功能, 对于更为细致的讲解, 可以看
​​​Python使用函数默认值实现函数静态变量的方法​​ **

​os.walk()​​ 的输出结果

命令为:

for content in os.walk('C:\\Users\\Eric\\Documents\\Python\\test'):
print content

结果是:
Python 使用 OS 模块实现目录遍历_静态变量_02
每一个 ​​​content​​​ 都是一个元组, 由 ​​(path, directory, filename)​​​
组成, 注意 ​​​directory​​​ 和 ​​filename​​ 均为 列表 .

方法2: 使用 os.walk()

完整代码

import os

allfile = []
# os.walk(path) 输出是一个 generator:
for path, directory, filename in os.walk('C:\\Users\\Eric\\Documents\\Python\\test'):
for direc in directory:
allfile.append(os.path.join(path, direc))

for path in allfile:
print path

输出结果

C:\Users\Eric\Documents\Python\test\f1
C:\Users\Eric\Documents\Python\test\f2
C:\Users\Eric\Documents\Python\test\f3
C:\Users\Eric\Documents\Python\test\jpg
C:\Users\Eric\Documents\Python\test\jpg\a

注意这里和上一个方法相比少了一个
​​​C:\Users\Eric\Documents\Python\test\jpg\getjpg.py​​​
不要在意细节!

方法2 总结

不错哦!

参考资料

  1. ​Python使用函数默认值实现函数静态变量的方法​