0
0
PythonHow-ToBeginner · 3 min read

How to Use os Module in Python: Basic Guide and Examples

The os module in Python provides functions to interact with the operating system, such as handling files and directories. You can import it using import os and then use its functions like os.getcwd() to get the current directory or os.listdir() to list files.
📐

Syntax

First, import the os module to access its functions. Then call functions using os.function_name(). For example, os.getcwd() returns the current working directory.

  • import os: Loads the module.
  • os.getcwd(): Gets current directory path.
  • os.listdir(path): Lists files in the given directory.
  • os.mkdir(path): Creates a new directory.
python
import os

# Get current working directory
current_dir = os.getcwd()

# List files in current directory
files = os.listdir(current_dir)

# Create a new directory named 'test_dir'
os.mkdir('test_dir')
💻

Example

This example shows how to get the current directory, list its files, create a new folder, and then remove it.

python
import os

# Get current directory
print('Current Directory:', os.getcwd())

# List files and folders
print('Contents:', os.listdir())

# Create a new directory
new_dir = 'example_dir'
os.mkdir(new_dir)
print(f'Directory "{new_dir}" created.')

# Remove the directory
os.rmdir(new_dir)
print(f'Directory "{new_dir}" removed.')
Output
Current Directory: /home/user Contents: ['file1.txt', 'file2.py', 'folder'] Directory "example_dir" created. Directory "example_dir" removed.
⚠️

Common Pitfalls

Common mistakes include trying to create a directory that already exists, or removing a directory that is not empty. Also, forgetting to import os causes errors. Always check if a directory exists before creating or deleting it.

python
import os

# Wrong: creating a directory without checking
# os.mkdir('test')  # Error if 'test' exists

# Right: check before creating
if not os.path.exists('test'):
    os.mkdir('test')

# Wrong: removing non-empty directory
# os.rmdir('test')  # Error if 'test' has files

# Right: remove files first or use shutil.rmtree for full removal
📊

Quick Reference

FunctionDescription
os.getcwd()Returns current working directory path
os.listdir(path='.')Lists files and folders in given path
os.mkdir(path)Creates a new directory at path
os.rmdir(path)Removes an empty directory
os.remove(path)Deletes a file
os.path.exists(path)Checks if a path exists
os.rename(src, dst)Renames a file or directory

Key Takeaways

Import the os module with 'import os' to access operating system functions.
Use os.getcwd() to find your current directory and os.listdir() to see files there.
Always check if a directory exists before creating or deleting it to avoid errors.
os.mkdir() creates directories; os.rmdir() removes empty directories only.
The os module helps manage files and folders easily from Python scripts.