Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python 历遍目录

$
0
0

Automate the Boring Stuff 学习笔记 01

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

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

假设有如下文件结构:


Python 历遍目录

程序代码如下:

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\walnutSUBFOLDER OF C:\delicious\walnut: waffles

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


Viewing all articles
Browse latest Browse all 9596

Trending Articles