在 Python 中浏览文件和子文件夹 [英] Browse files and subfolders in Python

查看:46
本文介绍了在 Python 中浏览文件和子文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想浏览当前文件夹及其所有子文件夹并获取所有扩展名为 .htm|.html 的文件.我发现可以找出一个对象是这样的目录还是文件:

I'd like to browse through the current folder and all its subfolders and get all the files with .htm|.html extensions. I have found out that it is possible to find out whether an object is a dir or file like this:

import os

dirList = os.listdir("./") # current directory
for dir in dirList:
  if os.path.isdir(dir) == True:
    # I don't know how to get into this dir and do the same thing here
  else:
    # I got file and i can regexp if it is .htm|html

最后,我想将所有文件及其路径放在一个数组中.这样的事情可能吗?

and in the end, I would like to have all the files and their paths in an array. Is something like that possible?

推荐答案

您可以使用 os.walk() 递归遍历一个目录及其所有子目录:

You can use os.walk() to recursively iterate through a directory and all its subdirectories:

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".html", ".htm")):
            # whatever

要构建这些名称的列表,您可以使用列表推导式:

To build a list of these names, you can use a list comprehension:

htmlfiles = [os.path.join(root, name)
             for root, dirs, files in os.walk(path)
             for name in files
             if name.endswith((".html", ".htm"))]

这篇关于在 Python 中浏览文件和子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆