Working with Paths

  • This lesson explains how to handle file and folder paths safely in Python applications.

  • What is the os Module?

    The os module provides functions to interact with the operating system.
    It is commonly used for:

    • Checking whether files or folders exist

    • Deleting files

    • Renaming files

    • Working with directories and paths

    The os module is part of Python’s standard library.

    Importing the os Module

    import os

    1.Checking Files in Python

    Before reading, deleting, or renaming a file, we should check if the file exists to avoid errors.

    os.path.exists()

    Purpose:
    Checks whether a file or folder exists.

    Syntax:

    os.path.exists("filename")

Checking File Existence

This program checks whether a file exists and prints a message.

import os

if os.path.exists("data.txt"):
    print("File exists")
else:
    print("File does not exist")


os.path.isfile()
  • Purpose:
    Checks whether the given path is a file.

    os.path.isfile("data.txt")


Checking Whether Path is a File

This program verifies if the given path refers to a file.

import os

if os.path.isfile("data.txt"):
    print("It is a file")
else:
    print("Not a file")

os.path.isdir()
  • Purpose:
    Checks whether the given path is a directory.

    os.path.isdir("myfolder")

    2️.Deleting Files in Python

    os.remove()

    Purpose:
    Deletes a file permanently.

    File must exist, otherwise an error occurs.

    Syntax:

    os.remove("filename")

Deleting a File Using os Module

This program checks for file existence before deleting it.

import os

if os.path.exists("old.txt"):
    os.remove("old.txt")
    print("File deleted successfully")
else:
    print("File not found")
  • 3.Renaming Files in Python

    os.rename()

    Purpose:
    Renames an existing file.

    Syntax:

    os.rename("old_name", "new_name")

Renaming a File Using os Module

This program renames a file after checking its existence.

import os

if os.path.exists("data.txt"):
    os.rename("data.txt", "backup.txt")
    print("File renamed successfully")
else:
    print("File does not exist")

Renaming File Inside a Directory

This program renames a file inside a specific folder.

import os

os.rename("files/report.txt", "files/report_old.txt")
  • Summary of Important Functions

    Function

    Use

    os.path.exists()

    Check file/folder existence

    os.path.isfile()

    Check if path is a file

    os.path.isdir()

    Check if path is a directory

    os.remove()

    Delete file

    os.rename()

    Rename file