TUTORIAL

Python Tutorial - File Directory Operation

It shows how Python file directory management operates

On this page

Python’s os module provides directory operations such as os.mkdir(), os.getcwd(), os.listdir(), os.chdir(), os.rename(), and os.rmdir(). A relative path is resolved from the process’s current working directory, which may differ from the folder containing the Python script. Use a temporary location when trying these operations so the example does not alter project or personal files.

Import os and understand the working directory

Import os before calling its functions. The process starts with a working directory chosen by how the program was launched; importing os does not set it. Relative paths in later calls are interpreted from this location. To avoid depending on the launch location, use an absolute path or first change to a directory your program controls.

Create a directory with os.mkdir()

os.mkdir(path) requires a path. When path is relative, Python creates the directory beneath the current working directory; an absolute path identifies its location directly. The call creates one directory level, so its parent must already exist. An existing name or missing parent causes an operating-system error.

Get the current working directory with os.getcwd()

os.getcwd() returns the process’s current working directory as a path string. It is useful for diagnosing where relative paths will be applied, but it does not report the directory containing the script. For more detail about this call, see the getcwd() function.

List directory contents with os.listdir()

os.listdir() without an argument returns the names in the current working directory. Pass a path to list a different directory. The returned values are entry names rather than full paths; join a name to its directory path when you need to open or inspect that entry. The order is not guaranteed, so sort the result when a stable display matters.

Change the working directory with os.chdir()

os.chdir(path) changes the working directory for the whole process, so subsequent relative paths use the new location. It affects other code running in that process as well. Call os.getcwd() after a change when the active location matters, and restore the previous location when a temporary change is part of a larger program.

Rename and remove directories

os.rename(source, destination) renames or moves a directory according to the supplied paths and filesystem rules. For predictable behavior, keep source and destination on the same filesystem; a destination conflict or permission restriction can prevent the operation. os.rmdir(path) removes a directory only when it contains no entries. It does not recursively delete contents, which helps prevent accidental removal of a populated tree. The example below creates and removes its own temporary directory.

The following complete example prints checks while creating, inspecting, changing, renaming, and removing directories in temporary storage. The finally block restores the original working directory even if an operation fails.

import os
import tempfile

with tempfile.TemporaryDirectory() as workspace:
    original_directory = os.getcwd()
    try:
        os.chdir(workspace)
        os.mkdir("reports")
        print(os.path.isdir("reports"))
        print(sorted(os.listdir()))

        os.chdir("reports")
        print(os.path.isabs(os.getcwd()))

        os.chdir("..")
        os.rename("reports", "archive")
        print(sorted(os.listdir()))
        os.rmdir("archive")
        print(os.listdir())
    finally:
        os.chdir(original_directory)
True
['reports']
True
['archive']
[]

Handle common directory-operation errors

A missing path or parent often indicates a typo or an unexpected working directory; inspect os.getcwd() and verify the path before retrying. os.mkdir() reports an error when the target already exists, while os.rename() may fail when its source is missing, the destination conflicts, or the filesystem disallows the move. os.rmdir() fails if the directory is not empty. Each operation can also fail when the process lacks permission. Catch OSError around the specific operation when the program can recover, and use its details to report which path needs attention. Do not suppress the error without checking that the intended directory state was reached.