获取文件夹中所有文件的绝对路径,无需遍历子文件夹

Getting the absolute paths of all files in a folder, without traversing the subfolders

my_dir = "/raid/user/my_dir"

是我文件系统上的一个文件夹,不是当前文件夹(即,它不是 os.getcwd() 的结果)。我想检索 my_dir 中第一层级的所有文件的绝对路径(即 my_dir 中所有文件的绝对路径,但不在 [=12= 的子文件夹中]) 作为字符串列表 absolute_paths。我需要它,以便以后使用 os.remove().

删除那些文件

这与

几乎相同的用例

Get absolute paths of all files in a directory

但不同之处在于我不想遍历文件夹层次结构:我只需要层次结构第一层的文件(深度 0?不确定这里的术语)。

您可以使用 os.path 模块和列表理解。

import os

absolute_paths= [os.path.abspath(f) for f in os.listdir(my_dir) if os.path.isfile(f)]

采用该解决方案很容易:只调用 os.walk() 一次,不要让它继续:

root, dirs, files = next(os.walk(my_dir, topdown=True))
files = [ os.path.join(root, f) for f in files ]
print(files)

您可以使用 os.scandir which returns an os.DirEntry 具有多种选项的对象,包括区分文件和目录的能力。

with os.scandir(somePath) as it:
    paths = [entry.path for entry in it if entry.is_file()]
print(paths)

如果您还想列出目录,当然,如果您想在列表中看到它们,您可以从列表理解中删除条件。

文档在 listDir 下也有此注释:

See also The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.