我有一个文件夹test
,我想根据以下规则从其中计算projects
,buildings
和txt_files
的数量。
对于projects
的数目,它仅等于第一层子目录的子文件夹的数目。对于buildings
的数目,如果它没有第二层子目录,则等于第一层子目录的数目;否则,请计算第二层子目录。
├─a
│ ├─a1
│ ├─a2
│ └─a3
│ ├─a3_1.txt
│ ├─a3_2.geojson
│ └─a3_3.txt
├─b
│ ├─b1
│ ├─b2
│ ├─b3
│ └─b4
├─c
│ ├─c1
│ ├─c2
│ └─c3
├─d
└─123.txt
对于以下示例结构:num_projects
是4
,其中包含第一层子文件夹:a, b, c, d
;而num_buildings
是11
,其中包含子目录:a1, a2, a3, b1, b2, b3, b4, c1, c2, c3 and d
;而num_txt
是3
。
到目前为止,我的解决方案是
import os
path = os.getcwd()
num_projects = 0
num_buildings = 0
num_txt = 0
for subdirs in os.listdir(path):
num_projects += 1
for root, dirnames, filenames in os.walk(path):
for dirname in dirnames:
num_buildings += 1
for filename in filenames:
if filename[-4:] == ".txt":
num_txt += 1
print("Number of projects is %d, number of buildings is %d, number of txt files is %d." %(num_projects, num_buildings, num_txt))
输出:
Number of projects is 5, number of buildings is 17, number of txt files is 3.
num_projects
和num_buildings
错误。我该如何纠正?谢谢。
答案 0 :(得分:1)
您在这里有两个不同的问题:
问题#1(num_projects
):os.listdir()
列出路径中的所有条目-不仅目录。
如何使其正确?
很简单,在增加计数器之前测试条目是文件还是目录。
问题2(num_buildings
):
您的规格:
如果没有第二层子目录,它等于第一层子目录的编号,否则,计算第二层子目录。
实际上根本没有在您的代码中实现-您只需计算所有目录和子目录。
如何使其正确?
尝试实施规范可能是一个很好的起点...请注意,os.walk()
可能不是此处的最佳解决方案。
答案 1 :(得分:1)
os.walk()是一个生成器,应该能够处理许多目录(和子目录)而不必担心内存。
这不是很优雅,但是可以尝试一下:
import os
projects = 0
buildings = 0
txt_files = 0
path = os.getcwd()
for root, directories, files in os.walk(path):
if root == path:
projects = len(directories)
for sub_dir in directories:
full_dir = os.path.join(root, sub_dir)
for root_, directories_, files_ in os.walk(full_dir):
if root_ == full_dir:
if directories_ == []:
buildings += 1
else:
buildings += (len(directories_))
for i in files:
if i.endswith('.txt'):
txt_files += 1
print("There are {} projects, {} buildings and {} text files".format(projects, buildings, txt_files))