Python Backend Dev Roadmap 4-Handle Files and Directories: File I/O, os, shutil, and pathlib modules

Elshad Karimov
2 min readApr 16, 2023

--

Handling files and directories is a crucial skill for any backend developer. In this post, we’ll explore Python’s built-in modules for file and directory management, providing examples and details to help you become proficient in this essential skill.

1. File I/O Reading and writing files is a common task for backend developers. Python’s built-in open() function makes it simple to work with files.

# Reading a file
with open("input.txt", "r") as file:
content = file.read()

# Writing to a file
with open("output.txt", "w") as file:
file.write("Hello, Python!")

# Reading a file line by line
with open("input.txt", "r") as file:
for line in file:
print(line.strip())

2. The os Module The os module provides a variety of operating system-dependent functions, such as working with paths, environment variables, and directories.

import os

# Get the current working directory
cwd = os.getcwd()

# Change the current working directory
os.chdir("/path/to/your/directory")

# List files and directories in the current directory
files = os.listdir()

# Create a new directory
os.mkdir("new_directory")

# Remove an empty directory
os.rmdir("empty_directory")

# Get environment variables
user = os.environ.get("USER")

3. The shutil Module The shutil module offers high-level file operations, such as copying or moving files and directories.

import shutil

# Copy a file
shutil.copy("source.txt", "destination.txt")

# Move a file
shutil.move("source.txt", "destination_folder")

# Copy a directory
shutil.copytree("source_directory", "destination_directory")

# Remove a directory and its contents
shutil.rmtree("directory_to_remove")

4. The pathlib Module The pathlib module provides a more object-oriented approach to working with files and directories.

from pathlib import Path

# Create a Path object
path = Path("file.txt")

# Get file properties
file_name = path.name
file_stem = path.stem
file_suffix = path.suffix
file_parent = path.parent

# Check if a path exists
path_exists = path.exists()

# Iterate through files in a directory
directory = Path("/path/to/your/directory")
for file in directory.iterdir():
print(file)

# Create a new directory
new_directory = Path("new_directory")
new_directory.mkdir()

# Remove an empty directory
empty_directory = Path("empty_directory")
empty_directory.rmdir()

Mastering file and directory handling in Python is vital for backend developers to manage and manipulate data effectively. Practice using these built-in modules in your projects to reinforce your learning and gain real-world experience.

#Python #BackendDevelopment #FileHandling #CareerDevelopment

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet