Python3 os.walk() 方法

Python 3 教程 · 2019-02-07 21:42:22

概述

os.walk() 方法用于通过在目录树种游走输出在目录中的文件名,向上或者向下。

在Unix,Windows中有效。

语法

walk()方法语法格式如下:

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

参数

  • top -- 根目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】。

  • topdown --可选,为True或者没有指定, 一个目录的的3-元组将比它的任何子文件夹的3-元组先产生 (目录自上而下)。如果topdown为 False, 一个目录的3-元组将比它的任何子文件夹的3-元组后产生 (目录自下而上)。

  • onerror -- 可选,是一个函数; 它调用时有一个参数, 一个OSError实例。报告这错误后,继续walk,或者抛出exception终止walk。

  • followlinks -- 设置为 true,则通过软链接访问目录。

返回值

该方法没有返回值。

实例

以下实例演示了 walk() 方法的使用:

#!/usr/bin/python3

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))

执行以上程序输出结果为:

./.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

点击查看所有 Python 3 教程 文章: https://www.codercto.com/courses/l/10.html

查看所有标签

The Shallows

The Shallows

Nicholas Carr / W. W. Norton & Company / 2011-6-6 / USD 15.95

"Is Google making us stupid?" When Nicholas Carr posed that question, in a celebrated Atlantic Monthly cover story, he tapped into a well of anxiety about how the Internet is changing us. He also crys......一起来看看 《The Shallows》 这本书的介绍吧!

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试