Перейти к содержимому

Как посчитать количество файлов в директории python

  • автор:

Python Count Number of Files in a Directory

In this article, we will see how to count the number of files present in a directory in Python.

If the directory contains many files and you want to count the number of files present in a directory before performing any operations. For example, you want to move all files from one directory to another. Still, before moving them, we can count how many files are present in a directory to understand its impact and the time required to perform that operation.

There are multiple ways to count files of a directory. We will use the following four methods.

Table of contents

How to count Files in a directory

Getting a count of files of a directory is easy as pie! Use the listdir() and isfile() functions of an os module to count the number of files of a directory. Here are the steps.

    Import os module

The os module provides many functions for interacting with the operating system. Using the os module, we can perform many file-related operations such as moving, copying, renaming, and deleting files.

Set counter to zero. This counter variable contains how many files are present in a directory.

Use for loop to Iterate the entries returned by the listdir() function. Using for loop we will iterate each entry returned by the listdir() function.

In each loop iteration, use the os.path.isfile(‘path’) function to check whether the current entry is a file or directory. If it is a file, increment the counter by 1.

Example: Count Number Files in a directory

The ‘account’ folder present on my system has three files. Let’s see how to print the count of files.

Output:

A compact version of the above code using a list comprehension.

Count all files in the directory and its subdirectories

Sometimes we need to count files present in subdirectories too. In such cases, we need to use the recursive function to iterate each directory recursively to count files present in it until no further sub-directories are available from the specified directory.

The os.walk() Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at the directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

For example, calling the os.walk(‘path’) will yield two lists for each directory it visits. The first list contains files, and the second list includes directories.

Let’s see how to use the os.walk() to count files present in a directory and its subdirectories.

Example:

The ‘account’ folder on my system contains three files and one subdirectory containing one file. so we must get a 4 as the final count.

Output:

scandir() to count all files in the directory

The scandir() function of an os module returns an iterator of os.DirEntry objects corresponding to the entries in the directory.

  • Use the os.scadir() function to get the names of both directories and files present in a given directory.
  • Next, iterate the result returned by the scandir() function using a for loop
  • Next, In each iteration of a loop, use the isfile() function to check if it is a file or directory. if yes increment the counter by 1

Note: If you need file attribute information along with the count, using the scandir() instead of listdir() can significantly increase code performance because os.DirEntry objects expose this information if the operating system provides it when scanning a directory.

Example:

Output:

fnmatch module to count all files in the directory

The fnmatch supports pattern matching, and it is faster.

  • For example, we can use fnmatch to find files that match the pattern *.* The * is a wildcard which means any name. So *.* indicates any file name with any extension, nothing but all files.
  • Next, we will use the filter() method to separate files returned by the listdir() function using the above pattern
  • In the end, we will count files using the len() function

Example:

Output:

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Related Tutorial Topics:

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

КОЛИЧЕСТВО ФАЙЛОВ В ПАПКЕ PYTHON

Python является одним из популярных языков программирования и часто используется для работы с файлами и директориями в операционной системе. Одной из распространенных задач является подсчет количества файлов в папке Python.

Для решения этой задачи можно использовать стандартную библиотеку Python — os. Код для подсчета количества файлов в папке выглядит следующим образом:

import os
path = «/path/to/directory»
files = os.listdir(path)
count = len(files)
print(«Number of files:», count)

В данном примере мы используем метод listdir для получения списка файлов в директории path , а затем используем функцию len для подсчета количества файлов. Результат выводится с помощью функции print .

Если вам нужно подсчитать только определенный тип файлов, например только файлы с расширением .txt, вы можете использовать следующий код:

import os
path = «/path/to/directory»
files = [f for f in os.listdir(path) if f.endswith(‘.txt’)]
count = len(files)
print(«Number of txt files:», count)

В этом примере мы используем списковое выражение для фильтрации файлов только с расширением .txt. Затем мы считаем количество файлов и выводим результат.

43 Рекурсивный обход файлов Python

Массовое переименование папок — Python и автоматизация — Работа с папками в Python

How to count the number of files in a directory using Python

How do I count only the files in a directory? This counts the directory itself as a file:

Mateen Ulhaq's user avatar

30 Answers 30

os.listdir() will be slightly more efficient than using glob.glob . To test if a filename is an ordinary file (and not a directory or other entity), use os.path.isfile() :

bryant1410's user avatar

Luke's user avatar

For all kind of files, subdirectories included (Python 2):

Only files (avoiding subdirectories):

MattDMo's user avatar

This is where fnmatch comes very handy:

If you want to count all files in the directory — including files in subdirectories, the most pythonic way is:

We use sum that is faster than explicitly adding the file counts (timings pending)

An answer with pathlib and without loading the whole list to memory:

Paul's user avatar

Short and simple

Somyadeep Shrivastava's user avatar

I am surprised that nobody mentioned os.scandir :

qed's user avatar

Marcus Riemer's user avatar

ninjrok's user avatar

This uses os.listdir and works for any directory:

this can be simplified with a generator and made a little bit faster with:

While I agree with the answer provided by @DanielStutzbach: os.listdir() will be slightly more efficient than using glob.glob .

However, an extra precision, if you do want to count the number of specific files in folder, you want to use len(glob.glob()) . For instance if you were to count all the pdfs in a folder you want to use:

This is an easy solution that counts the number of files in a directory containing sub-folders. It may come in handy:

You should get an output similar to this (with the placeholders changed, of course):

Пожалуйста, помогите с задачей на python!

Напишите программу, которая получает на вход путь до каталога (это может быть и просто корень диска) и выводит общее количество файлов и подкаталогов в нём. Также выведите на экран размер каталога в килобайтах (1 килобайт = 1024 байт).

Важный момент: чтобы посчитать, сколько весит каталог, нужно найти сумму размеров всех вложенных в него файлов.

Результат работы программы на примере python_basic\Module14:

E:\PycharmProjects\python_basic\Module14
Размер каталога (в Кб): 8.373046875
Количество подкаталогов: 7
Количество файлов: 15

Вот пример кода на Python:

def count_files_dirs_size(path):
size = 0
files = 0
dirs = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
size += os.path.getsize(fp)
files += 1
dirs += len(dirnames)
return (files, dirs, size)

path = input("Введите путь до каталога: ")
(files, dirs, size) = count_files_dirs_size(path)

print("Размер каталога (в Кб):", size/1024)
print("Количество подкаталогов:", dirs)
print("Количество файлов:", files)

При запуске программы, пользователь должен ввести путь до каталога.
В функции `count_files_dirs_size` мы с помощью `os.walk` проходим по всем директориям и файлам в указанном каталоге.
Затем мы увеличиваем переменные `size` для подсчета размера каталога (суммируем размеры всех файлов), `files` для подсчета количества файлов и `dirs` для подсчета количества подкаталогов.
В функции мы возвращаем кортеж, содержащий количество файлов, каталогов и размер каталога.

После этого, мы выводим на экран результаты с помощью функции `print()`. Размер каталога в килобайтах, подсчитывается делением переменной `size` на 1024.import os

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *