环境
- Windows 10
- Python 2.x 或 Python 3.x
方法
使用函数递归调用。
代码
直接贴代码啦,拿了就能用:
import os
"""
Input: 绝对路径或当前路径,例如 'D:/picture'
"""
def traverse_dir(current_dir):
file_list = os.listdir(current_dir)
for file in file_list:
path = os.path.join(current_dir, file)
if os.path.isdir(path):
# do something to this directory
traverse_dir(path)
if os.path.isfile(path):
# do something to this file
如果在遍历的过程中要对指定的文件名,或者指定的文件后缀进行操作,可使用如下函数,返回一个二元元组:
>>> os.path.splitext('hello world.py')
... ('hello world', '.py')
>>> os.path.splitext('hello world.py.jpg')
... ('hello world.py', '.jpg')
Reference
Wonder奇迹奇迹. (2015, April 8). python遍历文件夹下的文件. Retrieved from https://www.cnblogs.com/WonderHow/p/4403727.html