Как мне прочитать количество файлов в папке, используя Python?
Как узнать количество файлов в определенной папке с помощью Python? Пример кода будет потрясающим!
6 ответов
Чтобы пересчитать файлы и каталоги нерекурсивно, вы можете использовать os.listdir и взять свою длину.
Чтобы подсчитать файлы и каталоги рекурсивно, вы можете использовать os.walk для перебора файлов и подкаталогов в каталоге.
Если вы хотите только сосчитать файлы, которые не являются каталогами, вы можете использовать os.listdir и os.path.file , чтобы проверить, является ли каждая запись файлом:
Или, альтернативно, используя генератор:
Или вы можете использовать os.walk следующим образом:
Я нашел некоторые из этих идей из этот поток.
Вы можете использовать модуль glob:
Или, как предлагает Марк Байерс в своем ответе, если вы хотите только файлы:
Ответ Марка Байера прост, изящный и сочетается с духом питона.
Есть проблема, однако: если вы попытаетесь запустить ее для любой другой директории, чем «.», она не будет работать, поскольку os.listdir() возвращает имена файлов, а не полный путь. Эти два значения совпадают при перечислении текущего рабочего каталога, поэтому ошибка не обнаруживается в исходном файле выше.
Например, если вы в «/home/me» и вы перечислите «/tmp», вы получите (скажем) [‘flashXVA67’]. Вы будете тестировать «/home/me/flashXVA67» вместо «/tmp/flashXVA67» с помощью метода выше.
Вы можете исправить это, используя os.path.join(), например:
Кроме того, если вы собираетесь делать этот счет много и требуют производительности, вы можете сделать это без создания дополнительных списков. Здесь менее элегантное, нерегулярное, но эффективное решение:
Задача "Размер каталога"
Напишите программу, которая получает на вход путь до каталога (это может быть и просто корень диска) и выводит общее количество файлов и подкаталогов в нём. Также выведите на экран размер каталога в килобайтах (1 килобайт = 1024 байт).
Результат работы программы на примере C:\Downloads:
Размер каталога (в Кб): 8.373046875
Количество подкаталогов: 7
Количество файлов: 15
Создать родительский класс "Склад" и 3 подкласса ("принтеры"," сканеры", "ксероксы")
Начните работу над проектом «Склад оргтехники». Создайте класс, описывающий склад. А также класс.
Как выделить из строки название последнего каталога (без символов "\")
Дана строка, содержащая полное имя файла. Выделить из строки название последнего каталога (без.
Написать программу проверки правильности написания сочетаний "жи", "ши", "ча", "ща"
Помогите пожалуйста написать программу проверки правильности написания сочетаний "жи", "ши", "ча".
Сообщение было отмечено Zaouza как решение
Решение
ну ок, можно еще и так:
Regex для примерно следующих вариантов: "45345", "1234.", "323233.1"
Помогите плиз c regex для примерного следующих вариантов: "45345", "1234..", "323233.1". Т.е.
Курс Сириуса по Python. Задача на двумерные массивы "Кинотеатр"
Кинотеатр В кинотеатре n рядов по m мест в каждом. В двумерном массиве хранится информация о.
Задача для вывода слова "ёлочкой" шириной n букв
Помогите написать программу для вывода слова х "ёлочкой" шириной n букв по 1 букве на строке
Задача "Возвращение значений из функции". Ход конем
Вам дана строка, содержащая координату клетки на шахматном поле (например, “A2”). Напишите функцию.
Ошибка в коде (задача "частотный анализ")
Имеется следующая задача: Дан текст. Выведите все слова, встречающиеся в тексте, по одному на.
Задача "Без двух нулей подряд"
Требуется посчитать количество последовательностей длины n, состоящих из цифр от 0 до k−1 таких.
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.
Count Number of Files in Directory with Python
In Python, we can count the number of files in a directory easily with the listdir() function from the Python os module.
Note, the listdir() function returns a list of all names in a directory. To just get all files, you can check each name with the isdir() function.
If you want just the files of a certain extension, you can use the endswith() function to check the extension of each file.
When working with file systems, it can be useful to be able to get the number of files in a particular directory.
The Python os module provides us with a number of great functions to be able to perform many operating system tasks.
With the os module, we can count the number of files in a particular directory easily.
The listdir() function takes in a path and gets a list of all of the files in that directory. We can then find the length of that list to get the number of files in the directory.
Below is an example of how to get the number of files in a directory using Python.
listdir() returns all names in a directory, so the length of listdir() will count the number of items in a directory. To just get the number of files, and ignore the subdirectories, you can check each name with the isdir() function.
To just count the number of files of a certain extension, we can loop over the files and check the extensions with the help of the endswith() function.
Counting the Number of Files in a Folder and All Subfolders in Python
Another great os module function is the os module walk() function. The walk() function returns the entire tree of folders and subfolders given a path.
We can use the walk() function to get all folders and subfolders, and then iterate over the returned object to count the number of files in each folder and subfolder.
Let’s say we have the following folder structure.
In the 3 folders, we have a few files.
Let’s use the os walk() function to get the count of the files in each of the folders of our directory.
Below is the Python code which will allow you to get the number of files in each of the folders and subfolders of a given path.
From above, we know that listdir() treats all names as files. To filter out the subfolders, we can use the isdir() function.
If you want to get just files of a certain extension, then you can use the endswith() function.
Hopefully this article has been useful for you to understand how to count the number of files in a directory with Python.
Other Articles You'll Also Like:
- 1. Python Subtract Days from Date Using datetime timedelta() Function
- 2. Using Python to Print Degree Symbol
- 3. Zip Two Lists in Python
- 4. Create Empty Tuple in Python
- 5. Python nth Root – Find nth Root of Number with math.pow() Function
- 6. Decrement For Loop with range() in Python
- 7. Read First Line of File Using Python
- 8. How to Write Python Dictionary to File
- 9. How to Concatenate Tuples in Python
- 10. Convert String to Integer with int() in Python
About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.