简体   繁体   English

使用Python计算所有文件夹/子文件夹中的所有文件

[英]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.

相关问题 如何计算所有文件夹和子文件夹中具有特定扩展名的文件数 - How to count the number of files with a specific extension in all folders and subfolders Python:递归计算文件夹和子文件夹中的所有文件类型和大小 - Python: Recursively count all file types and sizes in folders and subfolders Python-使用python ftplib模块下载所有文件夹,子文件夹和文件 - Python - download all folders, subfolders, and files with the python ftplib module Python:如何在ALL文件,文件夹和子文件夹的名称中用下划线替换空格? - Python: How to replace whitespaces by underscore in the name of ALL files, folders and subfolders? 在python中从ftp文件夹和子文件夹读取所有文件 - Reading all files from ftp folders and subfolders in python 在文件夹和子文件夹中搜索所有Word和PDF文件中的字符串 - Search folders and subfolders for a string within all Word and PDF files 如何列出Google云端硬盘文件夹的所有文件,文件夹,子文件夹和子文件 - How to list all files, folders, subfolders and subfiles of a Google drive folder Python:更改所有文件夹和子文件夹中的文件名和文件夹名 - Python: Changing filenames and folder names in all folders and subfolders Python删除所有文件夹但不删除文件 - Python Deleting All Folders but not files python 可以加载所有子文件夹中没有完整名称的所有文件吗? - Can python load all files in all subfolders without the complete names?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM