
Python Basics: File System Operations
Python Basics: File System Operations
In this tutorial, you will learn about file system operations in Python using the pathlib and shutil modules. These operations include creating, moving, and deleting files and directories, as well as iterating over directory contents and searching for files using wildcards.
Introducing Files and the File System
First, let’s understand the basics. In the first three lessons, you will get an overview of file system operations, learn about the anatomy of a file, and understand the file system.
from pathlib import Path
# Creating a Path object from a string
file_path = Path('path/to/file.txt')
# Using Path.home() and Path.cwd()
home_directory = Path.home()
current_working_directory = Path.cwd()
# Checking whether a file path exists
file_path.exists()
# Understanding absolute vs relative paths
absolute_path = file_path.absolute()
relative_path = file_path.relative_to(home_directory)
# Resolving relative paths
resolved_path = file_path.resolve()
# Accessing file path components
file_name = file_path.name
file_suffix = file_path.suffixAccessing Files and Folders
The following lessons cover accessing files and folders, including creating path objects from strings, using operators, and accessing file path components.
# Using the forward slash operator
file_path / 'new_file.txt'
# Creating a directory
new_directory = Path('path/to/new_directory')
new_directory.mkdir()
# Creating a file
new_file = Path('path/to/new_file.txt')
new_file.touch()Creating and Searching for Files and Folders
In this section, you will learn how to create directories and files, iterate over directory contents, and search for files using glob methods and wildcards.
# Iterating over directory contents
for item in Path('path/to/directory').iterdir():
print(item)
# Searching for files using glob methods
matching_files = list(Path('path/to/directory').glob('*.txt'))
# Recursively matching
all_matching_files = list(Path('path/to/directory').rglob('*.txt'))Moving and Deleting Files and Folders
Finally, you’ll explore how to move and delete files and folders, including handling empty and non-empty folders.
# Moving a file
source = Path('path/to/source_file.txt')
destination = Path('path/to/destination_directory')
source.rename(destination / source.name)
# Deleting a file
Path('path/to/file_to_delete.txt').unlink()
# Deleting an empty folder
Path('path/to/empty_folder').rmdir()
# Deleting a non-empty folder
import shutil
shutil.rmtree('path/to/non_empty_folder')Reviewing File System Operations
The last section provides a summary of the file system operations covered in the tutorial and includes a quiz for you to test your knowledge.
By mastering these file system operations, you will be able to effectively work with files and directories in Python.
Remember to use the pathlib and shutil modules for cleaner, more readable, and cross-platform compatible code when working with file system operations in Python.






