
PYTHON — Files and Directories in Python
Programming isn’t about what you know; it’s about what you can figure out. — Chris Pine
Insights in this article were refined using prompt engineering methods.

PYTHON — Understanding Common Default Values in Python
# Working with Files and Directories in Python
In this article, you will learn how to work with files and directories in Python. You will be introduced to context managers and the with statement, which are commonly used in the Python standard library.
Opening and Manipulating Files
Let’s start by looking at an example where we open a file, read its content, manipulate the data, and then write the modified content to a new file.
from pathlib import Path
# Create a Path object using the first command-line argument
src_path = Path(sys.argv[1])
# Create a Path object for the destination file
dest_path = src_path.with_suffix('.ohno')
# Use context managers to open source and destination files
with src_path.open() as src, dest_path.open(mode='x') as dest:
for line in src:
modified_line = line.replace('o', '🚫')
dest.write(modified_line)In this example, we use the pathlib library to work with files. The with statement is used to ensure that the files are properly closed after the block of code is executed, even if an exception occurs. This approach provides a cleaner and more modern way to handle file operations compared to using the os module directly.
Working with Directories
Next, let’s explore how to iterate through the contents of a directory using the os module's scandir() method.
import os
import sys
# Use scandir() as a context manager to iterate through the directory contents
with os.scandir(sys.argv[1]) as entries:
for entry in entries:
print(f'{entry.name.ljust(16)} {entry.stat().st_size} bytes')In this example, we use the scandir() method as a context manager to obtain an iterator of directory entries. This allows us to iterate through the contents of the directory and perform operations on each entry.
Conclusion
In this tutorial, you learned how to work with files and directories in Python using context managers and the with statement. These techniques provide a clean and efficient way to handle file and directory operations while ensuring proper resource management. Experiment with the provided examples and consider incorporating these methods into your own Python projects for effective file and directory management.







