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

查看所有标签

Python for Data Analysis

Python for Data Analysis

Wes McKinney / O'Reilly Media / 2012-11-1 / USD 39.99

Finding great data analysts is difficult. Despite the explosive growth of data in industries ranging from manufacturing and retail to high technology, finance, and healthcare, learning and accessing d......一起来看看 《Python for Data Analysis》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码