Member-only story

Count Files and Folders using Python

Python Coding
2 min readNov 22, 2024

--

This Python script counts the number of files and directories within a specified path using the os module. Here's a breakdown of the code:

Code Breakdown

1. Importing the os Module

import os
  • The os module provides functions for interacting with the operating system, such as navigating directories and manipulating file paths.

2. Specifying the Path

PATH = r'C:\Users\IRAWEN\Downloads\1050'
  • PATH is the directory path where the script will search.
  • The r before the string indicates it is a raw string, meaning backslashes (\) are treated literally (not as escape characters).

3. Initializing Counters

files, dirs = 0, 0
  • files will store the count of files.
  • dirs will store the count of directories.

4. Iterating Through the Directory Structure

for root, dirnames, filenames in os.walk(PATH):
print('Looking in:', root)
dirs += len(dirnames)
files += len(filenames)
  • os.walk(PATH):
  • Traverses the directory tree starting…

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

Responses (1)