Series: Learning Python: A Comprehensive Beginner Level Tutorial Series 🚀

Python's os Module

Dive into the Python os module. Our comprehensive guide explains file operations, directory manipulation, and practical examples for effective file and system management in Python.
E
Edtoks2:34 min read

1. Changing the Working Directory:

os.chdir(path): Change the current working directory to the specified path.

import os
os.chdir("/path/to/new/directory")

 

2. Creating and Removing Directories:

os.mkdir(path): Create a new directory at the specified path.

os.makedirs(path): Create a directory and any necessary parent directories.

os.rmdir(path): Remove an empty directory.

os.removedirs(path): Remove a directory and any parent directories if they become empty.

import os
os.mkdir("new_directory")

os.rmdir("new_directory")

 

3. File and Directory Information:

os.path.exists(path): Check if a file or directory exists at the specified path.

os.path.isfile(path): Check if the path points to a file.

os.path.isdir(path): Check if the path points to a directory.

os.path.getsize(path): Get the size of a file in bytes.

 

import os

path = "example.txt"
if os.path.exists(path) and os.path.isfile(path):
    print(f"{path} exists and is a file.")

4. Listing Files and Directories:

os.listdir(path): Get a list of files and directories in the specified directory.

import os

files_and_dirs = os.listdir("/path/to/directory")

5. Renaming and Removing Files:

os.rename(src, dst): Rename a file or directory from src to dst.

os.remove(path): Remove a file.

import os
os.rename("old_file.txt", "new_file.txt")

os.remove("file_to_delete.txt")

 

6. Checking Permissions:

os.access(path, mode): Check if the current user has the specified permission (os.R_OK, os.W_OK, os.X_OK) on the file or directory.

import os

if os.access("file.txt", os.R_OK):
    print("Read permission granted.")

7. File Paths:

os.path.join(path1, path2, ...): Join one or more path components intelligently.

os.path.abspath(path): Get the absolute path of a file or directory.

import os

path = os.path.join("/path/to", "file.txt")
absolute_path = os.path.abspath(path)

These are some additional methods and functionality provided by the os module for working with files, directories, and paths in Python. You can combine these functions to perform various file system operations.