Python Directory Management
Python Directory Management refers to handling and interacting with directories
(folders) on a filesystem using Python. It includes creating, deleting, navigating and
listing directory contents programmatically. Python provides built-in modules
like os and os.path and the newer pathlib module, for this purpose.
os and os.path module
os module provides functions to interact with the operating system, such as managing
directories, files, processes and environment variables. It is cross-platform and adapts
to the underlying OS (e.g., Windows, Linux, macOS).
Creating new directory
os.mkdir(path): Creates a single directory at the specified path. Raises an error if
the directory already exists.
import os
os.mkdir("j:\\skd")
Renaming a directory:
os.rename(src, dst): Renames a directory (or file) from src to dst. The source
(src) must exist and the destination (dst) should not already exist.
For example, consider there is a file named ‘file1.txt’ in current working directory.
Now to just rename it :
os.rename("my_directory", "renamed_directory")
If renaming and moving the file to some other directory is required, then the code
snippet should be:
import os
os.renames('my_directory', 'renamed_directory')
Changing Current Working Directory (CWD)
os.chdir(path): Changes the current working directory to the specified path. After
changing, all relative paths are resolved concerning the new working directory. If
the specified path does not exist, an OSError is raised.
import os
print("Current directory :", os.getcwd())
# Changing directory
os.chdir('/home/nikhil/Desktop/')
print("Current directory :", os.getcwd())
Get Size of the Directory
os.path.getsize(path): Returns the size of a file in bytes. Use this with os.walk() to
calculate directory size. os.walk() iterates through all subdirectories and files in a
directory.Summing up file sizes gives the total directory size.
import os
print(os.path.getsize(os.getcwd()))
………………………………………………………………………………………………………………….
import os
import os
#print("Current directory :", os.getcwd()) print("Current directory :", os.getcwd())
# Changing directory
#os.chdir('e:\\skd') os.chdir('e:\\alpha')
print("Current directory :", os.getcwd()) print("Current directory :", os.getcwd())
os.rename('e:\\skd', 'e:\\alpha') os.chdir('C:\Python30')
print("Current directory :", os.getcwd())
print("Current directory :", os.getcwd())
os.rmdir('e:\\alpha')