如何使用递归目录搜索将文件计数设为零?

2024-05-19 19:48:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取特定文件名匹配的文件计数并写入字典。如果所有目录都包含一些文件(匹配或不匹配),那么下面的代码可以正常工作。但是,如果有一个空目录,它不会显示在字典中。Folder2为空,不显示在结果中。 我还想知道是否有一种方法,打印结果与一个正斜杠分隔符,而不是双反斜杠和正斜杠的组合? 我的代码:

import os
import re
def file_count_search(root_dir,keyword):
    dict={}
    for dirpath,dirnames,filenames in os.walk(root_dir,topdown=True):
        matches = re.findall(keyword, str(filenames))
        if keyword in matches:
            dict[os.path.join(root_dir,dirpath)] = len(matches)
    print dict
file_count_search("c://test","file")

我的结果:

{
    'c://test\\folder3\\subdir_folder3': 1, 
    'c://test': 1, 'c://test\\folder1': 3,
    'c://test\\folder3': 1
}

期望结果:

{
    'c:/test/folder3/subdir_folder3': 1,
    'c:/test': 1, 'c:/test/folder1': 3,
    'c:/test/folder2': 0,
    'c:/test/folder3': 1
}

Tags: 文件代码testimportre字典osdir
1条回答
网友
1楼 · 发布于 2024-05-19 19:48:26

如果给定目录中没有匹配的文件,matches将是一个空列表,因此keyword in matches将计算为False,并且不会向dict添加任何内容。你知道吗

尝试替换此行:

if keyword in matches:
  dict[os.path.join(root_dir,dirpath)] = len(matches)

仅此(根据Dan Farrell的注释,也用非保留变量名替换dict):

path_to_match_count[os.path.join(root_dir,dirpath)] = len(matches)

。。。对于这样的更新脚本:

import os
import re
def file_count_search(root_dir,keyword):
    path_to_match_count={}
    for dirpath,dirnames,filenames in os.walk(root_dir,topdown=True):
        matches = re.findall(keyword, str(filenames))
        path_to_match_count[os.path.join(root_dir,dirpath)] = len(matches)
    print path_to_match_count
file_count_search("c://test","file")

相关问题 更多 >