[英]Count all files in all folders/subfolders with Python
Which is the most efficient way to count all files in all folders and subfolders in Python? 哪种方法最有效地计算Python中所有文件夹和子文件夹中的所有文件? I want to use this on Linux systems.
我想在Linux系统上使用它。
Example output: 输出示例:
(Path files)
(路径文件)
/ 2
/ 2
/bin 100
/ bin 100
/boot 20
/启动20
/boot/efi/EFI/redhat 1
/ boot / efi / EFI / redhat 1
....
....
/root 34
/根34
....
....
Paths without a file should be ignored. 没有文件的路径应被忽略。
Thanks. 谢谢。
import os
print [(item[0], len(item[2])) for item in os.walk('/path') if item[2]]
It returns a list of tuples of folders/subfolders and files count in /path
. 它返回文件夹/子文件夹的元组列表和
/path
文件计数。
OR 要么
import os
for item in os.walk('/path'):
if item[2]:
print item[0], len(item[2])
It prints folders/subfolders and files count in /path
. 它打印文件夹/子文件夹和
/path
文件数。
If you want try faster solution, then you had to try to combine: 如果您想尝试更快的解决方案,则必须尝试结合使用:
os.scandir() # from python 3.5.2
iterate recursively and use: 递归迭代并使用:
from itertools import count
counter = count()
counter.next() # returns at first 0, next 1, 2, 3 ...
if counter.next() > 1000:
print 'dir with file count over 1000' # and use continue in for loop
Maybe that will be faster, because I think in os.walk
function are unnecessary things for you. 也许会更快,因为我认为
os.walk
函数对您来说是不必要的事情。
You can do it with os.walk()
; 您可以使用
os.walk()
做到这一点;
import os
for root, dirs, files in os.walk('/some/path'):
if files:
print('{0} {1}'.format(root, len(files)))
Note that this will also include hidden files, ie those that begin with a dot ( .
). 请注意,这还将包括隐藏文件,即以点(
.
)开头的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.