[英]Exclude files in a dictionary
我有一個腳本,可以在字典中收集目錄,其中的子目錄和文件數。 我需要排除該詞典的文件,但我無法做到這一點。
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
# Empty Dictionary that will store the Directory Tree
Directories = {}
# this value will act as a counter for folder key's
i = 0
# Assign your directory location to this variable
rootDir = r'Dir_path'
for dirName, subdirList, fileList in os.walk(rootDir):
Directories[str(i)] = dirName
i += 1
print(Directories)
老實說,我建議將Dir路徑存儲在列表中,而不是字典中,因為這樣可以更輕松地訪問它們
這應該給您所有目錄。
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)
path = r'C:\Users\user\Videos\xox'
import os
def fun(path):
path = path
lis_of_dir = [ (os.path.join(path,i),i) for i in os.listdir(path) if os.path.isdir(os.path.join(path,i))]
length = len(lis_of_dir)
sub = [{i[1]:fun(i[0])} for i in lis_of_dir]
return {'path':path,'no_of_dir':length,'sub_dir':sub}
print(fun(path))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.