Python 历遍目录

Automate the Boring Stuff 学习笔记 01

使用 os 模块的 walk() 函数可以实现历遍目录的操作,该函数接收一个绝对路径字符串作为必选参数,返回三个参数:

  • 当前目录——指程序当前工作目录——名称(字符串格式)
  • 当前目录——指程序当前所历遍到的目录——下所有子文件夹(列表格式)
  • 当前目录——指程序当前所历遍到的目录——下所有文件(列表格式)

假设有如下文件结构:

An example folder that contains three folders and four files

程序代码如下:

import os

for folderName, subfolders, filenames in os.walk(‘C:\\delicious’):
print(‘The current folder is ‘ + folderName)

for subfolder in subfolders:
print(‘SUBFOLDER OF ‘ + folderName + ‘: ‘ + subfolder)
for filename in filenames:
print(‘FILE INSIDE ‘ + folderName + ‘: ‘ + filename)

print(”)

程序输出结果为:

The current folder is C:\delicious
SUBFOLDER OF C:\delicious: cats
SUBFOLDER OF C:\delicious: walnut
FILE INSIDE C:\delicious: spam.txt

The current folder is C:\delicious\cats
FILE INSIDE C:\delicious\cats: catnames.txt
FILE INSIDE C:\delicious\cats: zophie.jpg

The current folder is C:\delicious\walnut
SUBFOLDER OF C:\delicious\walnut: waffles

The current folder is C:\delicious\walnut\waffles
FILE INSIDE C:\delicious\walnut\waffles: butter.txt.

posted @ 2016-06-27 15:25  东围居士  阅读(1461)  评论(0编辑  收藏  举报