python遍历目录,及参数用法说明

本文详细解释了Python os.walk函数的使用方法,包括topdown参数控制遍历顺序,onerror处理错误,以及如何利用root, dirs, files获取目录层级信息。通过实例演示了不同topdown值下的遍历结果。

python遍历目录,及参数用法说明
os.walk(“F:\testdemo”,top,topdown=True,οnerrοr=None,followlinks=False)遍历目录
参数说明:
top:表示需要遍历的目录树的路径
topdown的默认值是True,表示首先返回根目录树下的文件,然后遍历目录树下的子目录。值设为False时,则表示先遍历目录树下的子目录,返回子目录下的文件,最后返回根目录下的文件。

试举例说明:
设置topdown = False
import os
import os.path
l = os.walk(“F:\testdemo”,topdown=False)
for i in l:
print(i)

打印结果:
(‘F:\testdemo\aaa’, [], [])
(‘F:\testdemo\bbb’, [], [])
(‘F:\testdemo\ccc’, [], [])
(‘F:\testdemo\xxx’, [], [‘a.txt’, ‘b.txt’, ‘c.txt’])
(‘F:\testdemo’, [‘aaa’, ‘bbb’, ‘ccc’, ‘xxx’], [])
在这里插入图片描述
topdown = True
import os
import os.path
l = os.walk(“F:\testdemo”,topdown=True)
for i in l:
print(i)
打印结果:
(‘F:\testdemo’, [‘aaa’, ‘bbb’, ‘ccc’, ‘xxx’], [])
(‘F:\testdemo\aaa’, [], [])
(‘F:\testdemo\bbb’, [], [])
(‘F:\testdemo\ccc’, [], [])
(‘F:\testdemo\xxx’, [], [‘a.txt’, ‘b.txt’, ‘c.txt’])
在这里插入图片描述
onerror的默认值是“None”,表示忽略文件遍历时产生的错误。如果不为空,则提供一个自定义函数提示错误信息后继续遍历或抛出异常中止遍历。

该函数返回一个列表,列表中的每一个元素都是一个元组,该元组有3个元素,分别表示每次遍历的路径名,目录列表和文件列表。

import os
import os.path
l = os.walk(“F:\testdemo”,topdown=False)
print(l)
print(list(l))
print(l)打印结果:
<generator object walk at 0x0000024822DA64A0>
print(list(l))
[(‘F:\testdemo\aaa’, [], []), (‘F:\testdemo\bbb’, [], []), (‘F:\testdemo\ccc’, [], []), (‘F:\testdemo\xxx’, [], [‘a.txt’, ‘b.txt’, ‘c.txt’]), (‘F:\testdemo’, [‘aaa’, ‘bbb’, ‘ccc’, ‘xxx’], [])]
默认情况下,os.walk 不会遍历软链接指向子目录,若有需要请将followlinks设定为true

用root,dirs,files三个变量遍历目录的目录层级,目录层级的子目录,目录层级下的文件
for root,dirs,files in os.walk(r"F:\testdemo",topdown=False):
root :表示当前遍历到哪一层级目录了,目录的名字是谁
dirs:表示root下有哪些子目录
files:表示root下边有几个文件
topdown = False:
代码:
import os
import os.path
l = os.walk(“F:\testdemo”,topdown=False)
for i in l:
print(i)
print("*"*50)
for root,dirs,files in os.walk(“F:\testdemo”,topdown=False):
print(“front folder:”,root)
for name in dirs:
print(“folder name:”,os.path.join(root,name))
for name in files:
print(“file name:”,os.path.join(root,name))

打印结果:
(‘F:\testdemo\aaa’, [], [])
(‘F:\testdemo\bbb’, [], [])
(‘F:\testdemo\ccc’, [], [])
(‘F:\testdemo\xxx’, [], [‘a.txt’, ‘b.txt’, ‘c.txt’])
(‘F:\testdemo’, [‘aaa’, ‘bbb’, ‘ccc’, ‘xxx’], [])


front folder: F:\testdemo\aaa
front folder: F:\testdemo\bbb
front folder: F:\testdemo\ccc
front folder: F:\testdemo\xxx
file name: F:\testdemo\xxx\a.txt
file name: F:\testdemo\xxx\b.txt
file name: F:\testdemo\xxx\c.txt
front folder: F:\testdemo
folder name: F:\testdemo\aaa
folder name: F:\testdemo\bbb
folder name: F:\testdemo\ccc
folder name: F:\testdemo\xxx
在这里插入图片描述
topdown = True:
代码:
import os
import os.path
l = os.walk(“F:\testdemo”,topdown=True)
for i in l:
print(i)
print("*"*50)
for root,dirs,files in os.walk(“F:\testdemo”,topdown=True):
print(“front folder:”,root)
for name in dirs:
print(“folder name:”,os.path.join(root,name))
for name in files:
print(“file name:”,os.path.join(root,name))
运行结果:
(‘F:\testdemo’, [‘aaa’, ‘bbb’, ‘ccc’, ‘xxx’], [])
(‘F:\testdemo\aaa’, [], [])
(‘F:\testdemo\bbb’, [], [])
(‘F:\testdemo\ccc’, [], [])
(‘F:\testdemo\xxx’, [], [‘a.txt’, ‘b.txt’, ‘c.txt’])


front folder: F:\testdemo
folder name: F:\testdemo\aaa
folder name: F:\testdemo\bbb
folder name: F:\testdemo\ccc
folder name: F:\testdemo\xxx
front folder: F:\testdemo\aaa
front folder: F:\testdemo\bbb
front folder: F:\testdemo\ccc
front folder: F:\testdemo\xxx
file name: F:\testdemo\xxx\a.txt
file name: F:\testdemo\xxx\b.txt
file name: F:\testdemo\xxx\c.txt

在这里插入图片描述

<think>我们被要求回答关于Python遍历目录下文件的方法。根据提供的引用,有几种常见的方法: 1. 使用os.listdir():列出指定目录下的所有文件和子目录,但不递归。 2. 使用os.walk():递归遍历目录树,返回每个目录路径、子目录列表和文件列表。 3. 使用glob.glob():支持通配符匹配,可以递归匹配(使用**)但需要设置recursive参数。 4. 自定义递归函数:利用os.listdir()和递归来遍历所有子目录。 用户的问题:如何用Python遍历目录下的文件? 我们将介绍三种主要方法: 方法一:使用os.walk()(推荐用于递归遍历) 方法二:使用os.listdir()(仅当前目录,不递归) 方法三:使用glob.glob()(支持模式匹配,可递归) 同时,我们也可以展示一个自定义递归函数的例子(如引用[2]所示)。 注意:根据引用[1]的建议,如果需要递归遍历,推荐使用os.walk();如果只需要当前目录,使用os.listdir()或glob.glob()。 我们将按照以下结构回答: 1. 导入必要的模块(如os, glob) 2. 分别展示每种方法的代码示例 3. 简要说明每种方法的适用场景 此外,由于用户要求生成相关问题,我们将在最后添加相关问题。 注意:引用内容已经给出,我们在回答中适当引用。 开始回答: </think> ### Python遍历目录下文件的方法 在Python中,遍历目录文件主要有以下四种方法,根据引用内容整理如下: #### 1. **`os.walk()` 方法(推荐递归遍历)** ```python import os def traverse_files(root_dir): for root, dirs, files in os.walk(root_dir): for file in files: file_path = os.path.join(root, file) print(file_path) # 处理文件 # 示例:遍历D:\test目录 traverse_files(r"D:\test") ``` - **特点**:递归遍历所有子目录,返回三元组(当前目录路径、子目录列表、文件列表)[^1][^2]。 - **适用场景**:需要深度遍历整个目录树时使用。 #### 2. **`os.listdir()` 方法(非递归)** ```python import os def scan_dir(target_dir): for item in os.listdir(target_dir): item_path = os.path.join(target_dir, item) if os.path.isfile(item_path): print(item_path) # 处理文件 # 示例:遍历D:\目录(不递归子文件夹) scan_dir(r"D:\\") ``` - **特点**:仅列出当前目录下的文件和文件夹,不含子目录内容[^1][^3]。 - **适用场景**:只需处理单层目录时效率较高。 #### 3. **`glob.glob()` 方法(模式匹配)** ```python import glob # 遍历所有.txt文件(非递归) txt_files = glob.glob(r"D:\test\*.txt") # 递归遍历所有子目录中的.py文件 all_py_files = glob.glob(r"D:\test\**\*.py", recursive=True) ``` - **特点**:支持通配符(`*`, `?`, `**`),可灵活筛选文件类型。 - **适用场景**:需按扩展名或模式快速过滤文件。 #### 4. **自定义递归函数** ```python import os def recursive_traverse(root_path, file_list): for item in os.listdir(root_path): path = os.path.join(root_path, item) if os.path.isdir(path): recursive_traverse(path, file_list) # 递归子目录 else: file_list.append(path) # 添加文件路径 # 使用示例 file_list = [] recursive_traverse(r"D:\test", file_list) print(file_list) ``` - **特点**:手动实现递归控制,可定制处理逻辑[^2][^4]。 - **适用场景**:需要精细控制遍历过程时使用。 --- ### **方法对比与选择建议** | 方法 | 递归支持 | 易用性 | 适用场景 | |--------------------|----------|--------|------------------------------| | `os.walk()` | ✅ | ★★★★ | 深度遍历整个目录树(推荐) | | `os.listdir()` | ❌ | ★★★☆ | 单层目录快速访问 | | `glob.glob()` | ✅(需参数)| ★★★★ | 按模式匹配文件 | | 自定义递归 | ✅ | ★★☆ | 需高度定制遍历逻辑时 | > **实践提示**: > - 路径拼接务必使用 `os.path.join()` 保证跨平台兼容性 > - 检查路径类型时用 `os.path.isfile(path)` 和 `os.path.isdir(path)` > - 处理隐藏文件需额外过滤(如排除以`.`开头的文件) ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值