Python 如何计算子目录中的文件数?
我有以下文件结构,并希望使用python创建每个文件夹中文件数量的字典。底部的示例将转换为以下词典:Python 如何计算子目录中的文件数?,python,directory,Python,Directory,我有以下文件结构,并希望使用python创建每个文件夹中文件数量的字典。底部的示例将转换为以下词典: {Employee A: {Jan : 3}, {Feb : 2}, Employee B: {Jan : 2}, {Feb : 1}} 有人知道如何使用操作系统来迭代目录吗 员工A 简 文件1 文件2 文件3 二月 文件1 文件2 雇员B 简 文件1 文件2 二月 文件1 类似的内容可以让您迭代目录中的所有文件,并创建它们的列表。您可以根据需要对其进行修改: import os import
{Employee A: {Jan : 3}, {Feb : 2}, Employee B: {Jan : 2}, {Feb : 1}}
有人知道如何使用操作系统来迭代目录吗
员工A
简
文件1
文件2
文件3
二月
文件1
文件2
雇员B
简
文件1
文件2
二月
文件1
类似的内容可以让您迭代目录中的所有文件,并创建它们的列表。您可以根据需要对其进行修改:
import os
import glob
from pathlib import Path
error_log_list = []
def traverse_structure():
try:
root = r"C:\\Users\Whatever\Desktop\DirectoryToSearch"
# Change working directory
os.chdir(root)
print("Creating master list of the directory structure...\n")
# Traverse the folder structure
for folder, subfolders, files in os.walk(root):
# Pass over each file
for file in files:
absolute_path = os.path.join(folder,file)
# Create a master file list
file_paths_list.append(absolute_path)
except Exception as e:
error_log_list.append( "Failed to open the root directory specified "+root+"\n Error: "+str(e)+"\n" )
traverse_structure()
研究分析来自的输出 例如:
mydict = {}
for (root,dirs,files) in os.walk('testdir', topdown=False)
if len(files)>0:
mydict[root]=len(files)
print mydict
返回
{'testdir/EmployeeB/Jan': 2, 'testdir/EmployeeA/Feb': 2, 'testdir/EmployeeB/Feb': 1, 'testdir/EmployeeA/Jan': 3}
您可以非常轻松地解析这些键,以生成要查找的嵌套字典。使用操作系统库:
import os
parent = os.listdir(path) # return directory files to list
child = []
for x in parent:
if os.path.isdir(path +'/' + x):
child.append(os.listdir(path + '/' + x))
else
child.append('')
d = dict(zip(parent,child))
print(d)
这是用目录制作词典的基本逻辑。但是,这支持两个级别。我将把n级部分留给您自己。只需稍作调整,ActiveState Python配方就可以实现您想要的功能:
try:
reduce
except NameError: # Python 3
from functools import reduce
import os
def count_files_in_directories(rootdir):
""" Creates a nested dictionary that represents the folder structure
of rootdir with a count of files in the lower subdirectories.
"""
dir = {}
rootdir = rootdir.rstrip(os.sep)
start = rootdir.rfind(os.sep) + 1
for path, dirs, files in os.walk(rootdir):
folders = path[start:].split(os.sep)
subdir = len(files) if files else dict.fromkeys(files)
parent = reduce(dict.get, folders[:-1], dir)
parent[folders[-1]] = subdir
return list(dir.values())[0]
startdir = "./sample"
res = count_files_in_directories(startdir)
print(res) # -> {'Employee A': {'Feb': 2, 'Jan': 3}, 'Employee B': {'Feb': 1, 'Jan': 2}}
请注意,
/sample
目录是我为测试而创建的文件夹结构的根目录,它与问题中显示的文件夹结构完全相同。如果一个目录同时包含文件和子目录怎么办?在这种情况下,您希望字典的值是多少?您示例中的字典由于多种原因无效。嗨,John,欢迎使用StackOverflow。我知道在整个网站上随机出现的东西都有一些声誉要求,所以你可能已经点击了其中一个并回答了,但是如果没有,你的回答可能最好是以评论的形式出现(“像这样的低努力”回答通常会被否决或标记)。只是提醒一下:)@jedwards谢谢。我确实遇到了50个代表的注释要求,但我花了更多的精力来让它成为一个有效的答案。我认为os.chdir(root)
不是必需的(甚至不是一个好主意,因为它可能会给函数带来不希望的副作用),因为当前的工作目录对os.walk()
没有影响。您还需要在某个地方定义并初始化文件路径列表
变量。请深入解释os.chdir(root)问题?好的。1.不需要它(即不更改函数生成的列表
)。2.使用它意味着traverse\u structure()
函数可能会产生不希望的副作用,即更改当前工作目录。