简体   繁体   English

如何获得不同目录中的所有文件名?

[英]How can I get all filename in different directories?

Lets say the directories hierarchy looks like this: 可以说目录层次结构如下所示:

          A(root)
          |
B---------C--------D
|         |        |
fileB.h  fileC.png  fileD.py
         fileC1.jpg
          E
          |
         fileE.py

How can I access all the doc? 如何访问所有文档? Or just get the path. 或者只是获得路径。 Is there a way to iterlate all? 有没有办法迭代所有?

What I do: 我所做的:

path = sys.path[0]
for filename_dir in os.listdir(path):
     filename, ext = os.path.splitext(filename_dir)
     if ext == '.h':
         #do something
     elif ext == '.png'
         #do something
     .....

But as I know listdir can only access the directory where my program's py file located. 但是据我所知listdir只能访问程序的py文件所在的目录。

This gives only the dirs and files under a directory, but not recursively: 这仅给出目录下的目录和文件,但不递归:

import os

for filename in os.listdir(path):
    print filename

If you want to list absolute paths: 如果要列出绝对路径:

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]

If you want resursive search, this gives you an iterator that returns 3-tuples including the parent directory, list of directories, and list of files at each iteration: 如果要进行递归搜索,则可以使用迭代器在每次迭代时返回3元组,包括父目录,目录列表和文件列表:

for i,j,k in os.walk('.'):
    print i, j, k

For example: 例如:

    import os

    path = sys.path[0]

    for dirname, dirnames, filenames in os.walk(path):
        for subdirname in dirnames:
            print "FOUND DIRECTORY: ", os.path.join(dirname, subdirname)
        for filename in filenames:
            print "FOUND FILE: ", os.path.join(dirname, filename)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中抓取文件名并为每个文件名创建目录? - How can I scrape file names and create directories for each filename in Python? 通过单击按钮使用askopenfilename获取文件名后,如何在python的条目中显示该文件名 - After I use askopenfilename to get a filename by click a button, how can I show that filename in an Entry in python 如何获取文件上游两个目录的文件夹路径名? - How can I get the pathname of the folder two directories upstream of a file? 如何使用askopenfile获取有效的文件名 - How can I use askopenfile to get a valid filename 我如何使用正则表达式从字符串中获取文件名 - How can I get a Filename from a string using Regex 如何使用GAE获取上传文件的文件名? - How can I get the filename of an uploaded file with GAE? 如何列出目录中的所有目录 - How do I list all the directories in a directory 如何在特定目录(包括其子目录)中列出所有文件及其大小和创建日期? - How can I list all files with their sizes and date of creation in a specific directory including its sub-directories? 如何从 python 中的 tarfile 将文件提取到不同的目标文件名? - How can I extract files to a different destination filename from tarfile in python? 如何获取不同字典中相同键的所有值,并且字典存储在列表中 - how can i get all the values for the same key in different dictionary and dictionaries are stored in a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM