gpt4 book ai didi

python - 排除字典中的文件

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:00 25 4
gpt4 key购买 nike

我有一个脚本,它在字典中重新收集目录、子目录的数量和其中的文件。我需要排除这本词典的文件,但我无法做到这一点。

path="/home/tmp"

def PathToDict(path):
st = os.lstat(path)
result = {}
if S_ISDIR(st.st_mode):
result['Path'] = path
result['Subdir'] = {
name: PathToDict(os.path.join(path,name))
for name in os.listdir(path)}
result['Num_Subdir'] = int(len([i for i, j, k in os.walk(path)]))

这是重新收集所有文件夹的功能,但问题是也重新收集.sh或日志等文件。我正在尝试使用 os.path.isdir 方法,但我不能。

实际输出:

'Path': '/var/lib/jenkins/jobs/updates',
'Num_Subdir': 8,
'Subdir': {
'nextBuildNumber': {},
'config.xml': {},
'lastSuccessful': {},
'lastStable': {},
'builds': {
'Path': '/var/lib/jenkins/jobs/updates2',
'Num_Subdir': 7,
'Subdir': {
'lastStableBuild': {},
'lastSuccessfulBuild': {},
'1': {
'Path': '/var/lib/jenkins/jobs/updates3',
'Num_Subdir': 1,
'Subdir': {
'changelog.xml': {},
'injectedEnvVars.txt': {},
'build.xml': {},
'changelog.xml.temp2': {},
'log': {}

例如,我需要排除 .xml 和 .txt 的输出。在路径的根目录中,我也有文件,它们列在字典中,我也需要排除这些文件。

最佳答案

这应该为您提供所有目录。

import os

path = 'path_to_root_dir'

dir_list = []
exclude = ['directory', 'to', 'ignore']
for root, dirs, files in os.walk(path):
dirs[:] = [d for d in dirs if d not in exclude]
for dir in dirs:
dir_list.append(os.path.join(root,dir))

print(dir_list)

关于python - 排除字典中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56075700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com