下面是Python遍历子文件和所有子文件夹的代码实例的完整攻略。
背景
在进行文件处理时,我们经常需要对一个文件夹内的所有文件进行遍历,包括该文件夹内的所有子文件和子文件夹。Python提供了一种简单而强大的方法来实现这一目的。
实现方法
方法一: os.walk()函数
os.walk()
函数用于遍历一个目录内的所有子目录和文件。该函数返回一个三元组(root, dirs, files),其中root
为当前目录路径,dirs
为该目录内所有子目录的名称列表,files
为该目录内所有文件的名称列表。
通过对os.walk()
函数返回的三元组进行遍历,我们就可以依次遍历所有的子文件夹和子文件。
下面是一个示例代码:
import os
# 设置要遍历的路径
path = 'your/path/here'
for root, dirs, files in os.walk(path):
for file in files:
print(os.path.join(root, file))
方法二: pathlib库
pathlib
库是Python 3.4版本中新增的一个模块,它可以通过面向对象的方式高效地进行路径处理。
使用pathlib
库来遍历子文件和所有子文件夹与os.walk()
函数方式类似。不同之处在于,pathlib
库需要用Path
对象来表示路径,而不是字符串路径。
下面是一个示例代码:
from pathlib import Path
# 设置要遍历的路径
path = Path('your/path/here')
# 遍历所有的子文件夹和子文件
for child in path.glob('**/*'):
print(child)
示例说明
示例一: 遍历某个文件夹下的所有文件和文件夹
假设我们有一个包含多个文件和文件夹的目录结构,我们需要遍历该目录结构中的所有文件和文件夹。
使用os.walk()
函数的示例代码如下:
import os
# 设置要遍历的路径
path = 'your/path/here'
for root, dirs, files in os.walk(path):
for file in files:
print(os.path.join(root, file))
for dir in dirs:
print(os.path.join(root, dir))
使用pathlib
库的示例代码如下:
from pathlib import Path
# 设置要遍历的路径
path = Path('your/path/here')
# 遍历所有的子文件夹和子文件
for child in path.glob('**/*'):
print(child)
示例二: 按文件后缀名遍历某个文件夹下的所有文件
假设我们有一个包含多个文件的目录结构,我们需要遍历该目录结构中所有扩展名为.txt
和.md
的文件。
使用os.walk()
函数的示例代码如下:
import os
# 设置要遍历的路径
path = 'your/path/here'
# 遍历所有扩展名为.txt和.md的文件
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(('.txt','.md')):
print(os.path.join(root, file))
使用pathlib
库的示例代码如下:
from pathlib import Path
# 设置要遍历的路径
path = Path('your/path/here')
# 遍历所有扩展名为.txt和.md的文件
for file in path.glob('**/*.[tT][xX][tT]'):
print(file)
for file in path.glob('**/*.md'):
print(file)
总结
本文讲解了Python遍历子文件和所有子文件夹的代码实例的详细攻略,涵盖了两种实现方法以及两条实际应用的示例说明。