Посчитать количество папок 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.

  1. 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.
  2. create a counter variable Set counter to zero. This counter variable contains how many files are present in a directory.
  3. Use os.listdir() function The os.listdir(‘path’) function returns a list of files and directories present in the given directory.
  4. Iterate the result 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.
  5. Use isfile() function and increment counter by 1 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.
Читайте также:  Php объединить массив строку

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.

import os # folder path dir_path = r'E:\account' count = 0 # Iterate directory for path in os.listdir(dir_path): # check if current path is a file if os.path.isfile(os.path.join(dir_path, path)): count += 1 print('File count:', count) 

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

import os dir_path = r'E:\demos\files_demos\account' print(len([entry for entry in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, entry))]))

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.

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.

import os count = 0 for root_dir, cur_dir, files in os.walk(r'E:\account'): count += len(files) print('file count:', count)

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.

import os count = 0 dir_path = r'E:\account' for path in os.scandir(dir_path): if path.is_file(): count += 1 print('file count:', count)

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
import fnmatch dir_path = r'E:\demos\files_demos\account' count = len(fnmatch.filter(os.listdir(dir_path), '*.*')) print('File Count:', count)

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

Python Exercises and Quizzes

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

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Как подсчитать количество файлов в каталоге с помощью Python

Мне нужно подсчитать количество файлов в каталоге с помощью Python.
Я думаю, что самый простой способ – len(glob.glob(‘*’)) , но это также считает каталог как файл.

Можно ли считать только файлы в каталоге?

os.listdir() будет немного более эффективным, чем использование glob.glob . Чтобы проверить, является ли файл обычным файлом (а не каталогом или другим объектом), используйте os.path.isfile() :

import os, os.path # simple version for working with CWD print len([name for name in os.listdir('.') if os.path.isfile(name)]) # path joining version for other paths DIR = '/tmp' print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))]) 
import os path, dirs, files = os.walk("/usr/lib").next() file_count = len(files) 

Для всех типов файлов вложенные подкаталоги:

import os list = os.listdir(dir) # dir is your directory path number_files = len(list) print number_files 

Только файлы (избегая подкаталогов):

import os onlyfiles = next(os.walk(dir))[2] #dir is your directory path as string print len(onlyfiles) 

Здесь fnmatch очень удобен:

import fnmatch print len(fnmatch.filter(os.listdir(dirpath), '*.txt')) 
def directory(path,extension): list_dir = [] list_dir = os.listdir(path) count = 0 for file in list_dir: if file.endswith(extension): # eg: '.txt' count += 1 return count 
import os print len(os.listdir(os.getcwd())) 

Это использует os.listdir и работает для любого каталога:

import os directory = 'mydirpath' number_of_files = len([item for item in os.listdir(directory) if os.path.isfile(os.path.join(directory, item))]) 

это можно упростить с помощью генератора и сделать немного быстрее:

import os isfile = os.path.isfile join = os.path.join directory = 'mydirpath' number_of_files = sum(1 for item in os.listdir(directory) if isfile(join(directory, item))) 
def count_em(valid_path): x = 0 for root, dirs, files in os.walk(valid_path): for f in files: x = x+1 print "There are", x, "files in this directory." return x 
import os def count_files(in_directory): joiner= (in_directory + os.path.sep).__add__ return sum( os.path.isfile(filename) for filename in map(joiner, os.listdir(in_directory)) ) >>> count_files("/usr/lib") 1797 >>> len(os.listdir("/usr/lib")) 2049 

Переформатирование кода Luke.

import os print len(os.walk('/usr/lib').next()[2]) 

Я удивлен, что никто не упомянул os.scandir :

def count_files(dir): return len([1 for x in list(os.scandir(dir)) if x.is_file()]) 

Вот простая однострочная команда, которую я нашел полезной:

print int(os.popen("ls | wc -l").read()) 
import os total_con=os.listdir('') files=[] for f_n in total_con: if os.path.isfile(f_n): files.append(f_n) print len(files) 

Если вы будете использовать стандартную оболочку операционной системы, вы можете получить результат намного быстрее, чем использовать чистый пифонический путь.

import os import subprocess def get_num_files(path): cmd = 'DIR \"%s\" /A-D /B /S | FIND /C /V ""' % path return int(subprocess.check_output(cmd, shell=True)) 

Я нашел другой ответ, который может быть правильным в качестве принятого ответа.

for root, dirs, files in os.walk(input_path): for name in files: if os.path.splitext(name)[1] == '.TXT' or os.path.splitext(name)[1] == '.txt': datafiles.append(os.path.join(root,name)) print len(files) 

Я использовал glob.iglob для структуры каталогов, аналогичной

data └───train │ └───subfolder1 │ | │ file111.png │ | │ file112.png │ | │ . │ | │ └───subfolder2 │ │ file121.png │ │ file122.png │ │ . └───test │ file221.png │ file222.png 

Обе следующие опции возвращают 4 (как и ожидалось, т.е. не подсчитывают сами подпапки)

Я сделал это, и это вернуло количество файлов в папке (Attack_Data)… это отлично работает.

import os def fcount(path): #Counts the number of files in a directory count = 0 for f in os.listdir(path): if os.path.isfile(os.path.join(path, f)): count += 1 return count path = r"C:\Users\EE EKORO\Desktop\Attack_Data" #Read files in folder print (fcount(path)) 

Если вы хотите подсчитать все файлы в каталоге – включая файлы в подкаталогах, наиболее pythonic-способ:

import os file_count = sum(len(files) for _, _, files in os.walk(r'C:\Dropbox')) print(file_count) 

Мы используем сумму, которая быстрее, чем явное добавление количества файлов (время ожидания ожидания)

Источник

Как мне прочитать количество файлов в папке, используя Python?

Чтобы пересчитать файлы и каталоги нерекурсивно, вы можете использовать os.listdir и взять свою длину. Чтобы подсчитать файлы и каталоги рекурсивно, вы можете использовать os.walk для перебора файлов и подкаталогов в каталоге. Если вы хотите только сосчитать файлы, которые не являются каталогами, вы можете использовать os.listdir и os.path.file , чтобы проверить, является ли каждая запись файлом:

import os.path path = '.' num_files = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]) 
num_files = sum(os.path.isfile(os.path.join(path, f)) for f in os.listdir(path)) 
>>> import glob >>> print len(glob.glob('/tmp/*')) 10 
>>> print [f for f in glob.glob('/tmp/*') if os.path.isfile(f)] ['/tmp/foo'] >>> print sum(os.path.isfile(f) for f in glob.glob('/tmp/*')) 1 

@lunaryorn — если вы хотите скрытые файлы в текущем каталоге, используйте glob(‘.*’) . Если вы хотите все, включая скрытые файлы, используйте glob(‘.*’) + glob(‘*’) .

Ответ Марка Байера прост, изящный и сочетается с духом питона.

Есть проблема, однако: если вы попытаетесь запустить ее для любой другой директории, чем «.», она не будет работать, поскольку os.listdir() возвращает имена файлов, а не полный путь. Эти два значения совпадают при перечислении текущего рабочего каталога, поэтому ошибка не обнаруживается в исходном файле выше.

Например, если вы в «/home/me» и вы перечислите «/tmp», вы получите (скажем) [‘flashXVA67’]. Вы будете тестировать «/home/me/flashXVA67» вместо «/tmp/flashXVA67» с помощью метода выше.

Вы можете исправить это, используя os.path.join(), например:

import os.path path = './whatever' count = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]) 

Кроме того, если вы собираетесь делать этот счет много и требуют производительности, вы можете сделать это без создания дополнительных списков. Здесь менее элегантное, нерегулярное, но эффективное решение:

import os def fcount(path): """ Counts the number of files in a directory """ count = 0 for f in os.listdir(path): if os.path.isfile(os.path.join(path, f)): count += 1 return count # The following line prints the number of files in the current directory: path = "./whatever" print fcount(path) 

Источник

Оцените статью