微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决获取绝对文件路径列表并忽略点目录/文件python

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

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

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

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

// Gets the footer link color,if assigned by user.
if (get_theme_mod('theme_footer_link_color')) {
    $footerLinkColorAttribute = 'color:' . get_theme_mod('theme_footer_link_color','default_value') . ';';
}

function add_customizer_link_color_attribute_to_footer_menu_links($atts,$item,$args){
    if ($args->theme_location == 'footerNavLocation') {
      $atts['style'] = $footerLinkColorAttribute;
    }
return $atts;
}
add_filter('nav_menu_link_attributes','add_customizer_link_color_attribute_to_footer_menu_links',10,3);

示例:

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

解决方法

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

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

当您的起始路径已经是绝对路径时,在其上调用 os.path.abspath 是多余的,但我想在伟大的方案中,您可以将其保留。

,

不要使用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 等来节省一些开销,但这确实取决于您的需求

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。