Python 列出目录中的所有文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39909655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:53:44  来源:igfitidea点击:

Listing of all files in directory?

pythonpathlib

提问by Akrios

Can anybody help me create a function which will create a list of all files under a certain directory by using pathliblibrary?

任何人都可以帮助我创建一个函数,该函数将使用pathlib库创建某个目录下所有文件的列表?

Here, I have a:

在这里,我有一个:

enter image description here

在此处输入图片说明

I have

我有

  • c:\desktop\test\A\A.txt

  • c:\desktop\test\B\B_1\B.txt

  • c:\desktop\test\123.txt

  • c:\desktop\test\A\A.txt

  • c:\desktop\test\B\B_1\B.txt

  • c:\desktop\test\123.txt

I expected to have a single list which would have the paths above, but my code returns a nested list.

我希望有一个包含上述路径的列表,但我的代码返回一个嵌套列表。

Here is my code:

这是我的代码:

from pathlib import Path

def searching_all_files(directory: Path):   
    file_list = [] # A list for storing files existing in directories

    for x in directory.iterdir():
        if x.is_file():

           file_list.append(x)
        else:

           file_list.append(searching_all_files(directory/x))

    return file_list


p = Path('C:\Users\akrio\Desktop\Test')

print(searching_all_files(p))

Hope anybody could correct me.

希望有人能纠正我。

回答by prasastoadi

Use Path.glob()to list all files and directories. And then filter it in a List Comprehensions.

使用Path.glob()列出所有文件和目录。然后在List Comprehensions 中过滤它。

p = Path(r'C:\Users\akrio\Desktop\Test').glob('**/*')
files = [x for x in p if x.is_file()]

More from the pathlibmodule:

更多来自pathlib模块:

回答by MichielB

from pathlib import Path
from pprint import pprint

def searching_all_files(directory):
    dirpath = Path(directory)
    assert(dirpath.is_dir())
    file_list = []
    for x in dirpath.iterdir():
        if x.is_file():
            file_list.append(x)
        elif x.is_dir():
            file_list.extend(searching_all_files(x))
    return file_list

pprint(searching_all_files('.'))

回答by tk3

If your files have the same suffix, like .txt, you can use rglobto list the main directory and all subdirectories, recursively.

如果您的文件具有相同的后缀,例如.txt,您可以使用rglob递归列出主目录和所有子目录。

paths = list(Path(INPUT_PATH).rglob('*.txt'))

If you need to apply any useful Path functionto each path. For example, accessing the nameproperty:

如果您需要将任何有用的Path 函数应用于每个路径。例如,访问name属性:

[k.name for k in Path(INPUT_PATH).rglob('*.txt')]

Where INPUT_PATHis the path to your main directory, and Pathis imported from pathlib.

INPUT_PATH主目录的路径在哪里,Pathpathlib.

回答by HMan06

Using pathlib2 is much easier,

使用 pathlib2 更容易,

from pathlib2 import Path

path = Path("/test/test/")
for x in path.iterdir():
    print (x)

回答by Aman Jaiswal

You can use os.listdir(). It will get you everything that's in a directory - files and directories.

您可以使用 os.listdir()。它将为您提供目录中的所有内容 - 文件和目录。

If you want just files, you could either filter this down using os.path:

如果你只想要文件,你可以使用 os.path 过滤掉它:

from os import listdir
from os.path import isfile, join
onlyfiles = [files for files in listdir(mypath) if isfile(join(mypath, files))]

or you could use os.walk() which will yield two lists for each directory it visits - splitting into files and directories for you. If you only want the top directory you can just break the first time it yields

或者您可以使用 os.walk() 它将为它访问的每个目录生成两个列表 - 为您拆分为文件和目录。如果您只想要顶级目录,则可以在第一次产生时中断

from os import walk
files = []
for (dirpath, dirnames, filenames) in walk(mypath):
    files.extend(filenames)
    break

回答by Akrios

def searching_all_files(directory: Path):   
    file_list = [] # A list for storing files existing in directories

    for x in directory.iterdir():
        if x.is_file():
            file_list.append(x)#here should be appended
        else:
            file_list.extend(searching_all_files(directory/x))# need to be extended

    return file_list

回答by Vineet Sharma

import pathlib

def get_all_files(dir_path_to_search):
    filename_list = []

    file_iterator = dir_path_to_search.iterdir()

    for entry in file_iterator:
            if entry.is_file():
                #print(entry.name)
                filename_list.append(entry.name)

    return filename_list

The function can we tested as -

我们可以测试该功能 -

dir_path_to_search= pathlib.Path("C:\Users\akrio\Desktop\Test")
print(get_all_files(dir_path_to_search))