Land your first dev job — 100% money-back guarantee.
Continue

Paths and Utils in Python

Learn how to work with file system paths and common utility modules in Python. Understand how to handle files safely using pathlib, os, and shutil.

Working with File Paths

In Python, file paths can be handled in multiple ways. Older approach: - Using the os module Modern and recommended approach: - Using pathlib module (introduced in Python 3.4) pathlib provides an object-oriented way to work with paths and is easier for beginners.

Creating a Path Object

Use pathlib to create and inspect paths.

Joining Paths Safely

Use the / operator to join paths safely across operating systems.

Checking Files and Directories

pathlib makes it easy to check whether a file or directory exists.

Check if File Exists

Use exists(), is_file(), and is_dir() methods.

Creating and Deleting Files

You can create and remove files using pathlib and os utilities.

Create and Write to a File

Use write_text() to create and write to a file.

Delete a File

Use unlink() to delete a file.

Working with Directories

You can create and remove directories using pathlib and shutil.

Create a Directory

Use mkdir() to create a new directory.

Remove a Directory

Use shutil to remove directories safely.

Useful OS Utilities

Although pathlib is recommended for paths, the os module still provides many useful utilities.

Get Current Working Directory

Use os.getcwd() to get the current directory.

List Directory Contents

Use os.listdir() to list files and folders.