OS 模块的 Python walk() 方法通过以自上而下或自下而上的方式遍历树来显示指定目录树中的文件名。
对于树中的每个目录,os.walk() 方法会生成一个 3 元组,其中包含目录路径、当前目录中的子目录列表和文件名。
语法
以下是 Python os.walk() 方法的语法 -
os.walk(top, topdown, onerror, followlinks)
参数
Python os.walk() 方法接受以下参数 -
- top − 表示根目录的路径。
- topdown − 这是一个可选参数。如果设置为 “True” (默认值),则从上到下遍历目录树。如果为 “False”,则从下到上遍历它。
- onerror − 它用于处理潜在错误。
- followlinks − 它也是一个可选参数,如果设置为 true,则将跟踪符号链接。
返回值
Python os.walk() 方法返回一个包含 dirpath、dirnames、filenames 的 3 元组。
例以下示例显示了 walk() 方法的用法。在这里,该方法将从当前目录开始遍历。
import os
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
让我们编译并运行上面的程序,这将从下到上扫描所有目录和子目录。
./tmp/test.py
./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp
./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp
如果将 topdown 的值更改为 True,则将得到以下结果 -
./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp
./tmp/test.py
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp
./tmp/test.py
例
也可以显示具有特定扩展名的文件。如您在以下示例中所见,我们只列出了扩展名为 “.py” 的文件。
import os
print("Listing Python file:")
for dirpath, dirnames, filenames in os.walk("."):
for filename in filenames:
if filename.endswith(".py"):
print(filename)
在运行上述代码时,它将显示以下输出 -
Listing Python file:
isatty.py
ftrunc.py
fstat.py
mkdrs.py
renames.py
lsta.py
openp.py
rmdir.py
cwd.py
pthcnf.py
isatty.py
ftrunc.py
fstat.py
mkdrs.py
renames.py
lsta.py
openp.py
rmdir.py
cwd.py
pthcnf.py