Pyhton遍历文件夹

这是一个常用的功能,可以有两种方法,os.walkos.listdir

文档是这么解释的:

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries ‘.’ and ‘..’ even if they are present in the directory.

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

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

代码如下:

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*- 
import os
def list_dir(rootDir):
list_dirs = os.walk(rootDir)
for root, dirs, files in list_dirs:
for d in dirs:
print os.path.join(root, d)
for f in files:
print os.path.join(root, f)
1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*- 
import os
def list_dir(rootDir):
for lists in os.listdir(rootDir):
path = os.path.join(rootDir, lists)
print path
if os.path.isdir(path):
list_dir(path)

对于第一种方法,输出总是先文件夹后文件名的,对于第二种,则是按照目录树结构以及按照首字母排序进行输出的。

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×