获取绝对文件路径列表并忽略点目录/文件

问题描述 投票:0回答:2

如何获取指定目录内的绝对文件路径并忽略点(.)目录和点(.)文件

我有以下解决方案,它将递归地提供目录中的完整路径,

帮助我以最快的方式列出具有完整路径的文件并忽略 .directories/ 和 .files 来列出

(目录可能包含100到5亿个文件)

import os

def absoluteFilePath(directory):
    for dirpath,_,filenames in os.walk(directory):
        for f in filenames:
            yield os.path.abspath(os.path.join(dirpath, f))


for files in absoluteFilePath("/my-huge-files"):
    #use some start with dot logic ? or any better solution

示例:

/my-huge-files/project1/file{1..100} # Consider all files from file1 to 100
/my-huge-files/.project1/file{1..100} # ignore .project1 directory and its files (Do not need any files under .(dot) directories)
/my-huge-files/project1/.file1000 # ignore .file1000, it is starts with dot 
python python-3.x linux os.walk
2个回答
0
投票

os.walk
根据定义访问层次结构中的每个文件,但您可以使用简单的文本过滤器选择实际打印的文件。

for file in absoluteFilePath("/my-huge-files"):
    if '/.' not in file:
        print(file)

当你的起始路径已经是绝对路径时,在其上调用

os.path.abspath
是多余的,但我想在伟大的计划中,你可以将其保留。


0
投票

不要使用

os.walk()
,因为它会访问每个文件
相反,请退回到
.scandir()
.listdir()
并编写自己的实现

您可以使用

pathlib.Path(test_path).expanduser().resolve()
完全展开路径

import os
from pathlib import Path

def walk_ignore(search_root, ignore_prefixes=(".",)):
    """ recursively walk directories, ignoring files with some prefix
        pass search_root as an absolute directory to get absolute results
    """
    for dir_entry in os.scandir(Path(search_root)):
        if dir_entry.name.startswith(ignore_prefixes):
            continue
        if dir_entry.is_dir():
            yield from walk_ignore(dir_entry, ignore_prefixes=ignore_prefixes)
        else:
            yield Path(dir_entry)

您也许可以通过闭包节省一些开销,强制一次 Path,

yield
.name
等,但这实际上取决于您的需求

也不是针对你的问题,而是与之相关;如果文件非常小,您可能会发现将它们打包在一起(将多个文件打包在一个文件中)或调整文件系统块大小将获得更好的性能

最后,一些文件系统带有特定于它们的奇怪警告,您可能会用符号链接循环等奇怪的东西来打破它

© www.soinside.com 2019 - 2024. All rights reserved.