Home  >  Article  >  Backend Development  >  How to traverse a folder in python

How to traverse a folder in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-08-02 13:22:556973browse

How to traverse a folder in python

方法一 : 利用函数 os.walk()

os.walk() 会返回三元元组 (dirpath, dirnames, filenames)

dirpath : 根路径 (字符串)

dirnames : 路径下的所有目录名 (列表)

filenames : 路径下的所有非目录文件名 (列表) 

相关推荐:《Python视频教程

其中目录名和文件名都是没有加上根路径的,所以需要完整路径时需要将目录名或文件名与根路径连接起来。

示例 :

import os 
root = "C:\\dir" 
for dirpath, dirnames, filenames in os.walk(root): 
    for filepath in filenames:
        print os.path.join(dirpath, filepath)

方法二 : 利用函数 os.listdir(), os.path.isdir(), os.path.isfile()

os.listdir() 可以列出路径下所有文件和目录名,但是不包括当前目录., 上级目录.. 以及子目录下的文件.

os.path.isfile() 和 os.path.isdir() 判断当前路径是否为文件或目录

示例 :

import os 
def listDir(rootDir):
    for filename in os.listdir(rootDir):
        pathname = os.path.join(rootDir, filename)
        if (os.path.isfile(filename)):
            print pathname
        else:
            listDir(pathname)

The above is the detailed content of How to traverse a folder in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn