Every file stored on a computer has a unique location called a file path. Whether you are reading a text file, saving a report, loading a dataset, or creating a new folder, Python needs to know where the file is located. Understanding file paths and directories is therefore an essential skill for every Python programmer.
Python provides the built-in os module to interact with the operating system. Using this module, you can navigate folders, create directories, rename files, delete folders, and retrieve information about the current working directory. These features are widely used in automation, data analytics, web development, and system administration.
In this lesson, you will learn what file paths and directories are, understand the difference between absolute and relative paths, work with the current working directory, change directories, and explore practical examples using Python’s os module.
After completing this lesson, you will be able to:
os module.A file path is the complete address of a file or folder stored on a computer. Python uses file paths to locate files for reading, writing, copying, moving, or deleting.
For example:
C:\Users\Rahul\Documents\student.txt
or on Linux/macOS:
/home/rahul/Documents/student.txt
Without the correct file path, Python cannot locate the required file.
Python mainly works with two types of file paths.
An absolute path specifies the complete location of a file from the root directory.
Example (Windows):
C:\Users\Rahul\Documents\Python\data.csv
Example (Linux/macOS):
/home/rahul/Documents/Python/data.csv
An absolute path always points to the same file regardless of the current working directory.
A relative path specifies the location of a file relative to the current working directory.
Example:
data.csv
or
files/data.csv
Relative paths are shorter and make programs easier to move between different systems.
| Feature | Absolute Path | Relative Path |
|---|---|---|
| Starts From | Root Directory | Current Directory |
| Length | Usually Longer | Usually Shorter |
| Portability | Less Portable | More Portable |
| Recommended For | Fixed Locations | Projects and Applications |
A directory (also called a folder) is a location used to organize files and other directories.
Example:
Python_Project/
│
├── data/
│ ├── students.csv
│ ├── sales.csv
│
├── reports/
│ ├── report.txt
│
└── main.py
Directories help organize project files and improve project management.
os ModuleThe os module provides functions for interacting with the operating system.
import os
The os module is included with Python, so no installation is required.
The Current Working Directory (CWD) is the folder where Python is currently executing the program.
You can display it using os.getcwd().
import os
print(os.getcwd())
Sample Output
C:\Users\Rahul\PythonProject
This function is extremely useful when working with relative file paths.
The os.chdir() function changes the current working directory.
os.chdir(path)
import os
os.chdir("C:\\Users\\Rahul\\Documents")
print(os.getcwd())
Sample Output
C:\Users\Rahul\Documents
After changing the directory, all relative paths are resolved from the new location.
| Application | Purpose |
|---|---|
| Data Analytics | Locate datasets stored in project folders. |
| Automation Scripts | Navigate directories automatically. |
| Web Applications | Access uploaded files. |
| Backup Software | Copy files between directories. |
| Machine Learning | Load datasets from project folders. |
| System Administration | Manage folders and system files. |
import os
print("Current Directory:")
print(os.getcwd())
os.chdir("Documents")
print("New Directory:")
print(os.getcwd())
Sample Output
Current Directory:
C:\Users\Rahul
New Directory:
C:\Users\Rahul\Documents
Consider the following program.
import os
print(os.getcwd())
os.chdir("Documents")
print(os.getcwd())
Execution Steps
os module.os.chdir() changes the current directory.Sample Output
C:\Users\Rahul
C:\Users\Rahul\Documents
os module before using its functions.In this section, you learned what file paths and directories are, explored the differences between absolute and relative paths, imported the os module, displayed the current working directory using os.getcwd(), and changed directories using os.chdir(). You also explored practical examples, execution flow, and common beginner mistakes. In the next section, you will learn how to create, rename, list, and remove directories using functions such as os.mkdir(), os.makedirs(), os.listdir(), os.rename(), and os.rmdir().
In the previous section, you learned how to create, rename, list, and remove directories using Python’s os module. While these functions help manage folders, Python also provides the powerful os.path module for working with file paths. This module allows you to check whether files exist, determine whether a path represents a file or directory, combine path components safely, extract file names, and retrieve file information.
The os.path module is extremely useful because it creates platform-independent code that works correctly on Windows, Linux, and macOS without changing path separators manually.
In this section, you will learn how to use the most commonly used functions in the os.path module with practical examples.
os.path?The os.path module provides functions for working with file and directory paths.
import os
The os.path module is automatically available after importing os.
The os.path.exists() function checks whether a file or directory exists.
os.path.exists(path)
import os
print(os.path.exists("students.csv"))
Sample Output
True
If the specified path does not exist, the function returns False.
The os.path.isfile() function returns True if the specified path points to a file.
import os
print(os.path.isfile("students.csv"))
Output
True
The os.path.isdir() function checks whether the specified path is a directory.
import os
print(os.path.isdir("Data"))
Output
True
The os.path.join() function combines multiple path components using the correct separator for the operating system.
os.path.join(path1, path2)
import os
path = os.path.join("Data", "students.csv")
print(path)
Sample Output (Windows)
Data\students.csv
Sample Output (Linux/macOS)
Data/students.csv
Using os.path.join() makes your code portable across different operating systems.
The os.path.basename() function extracts the file name from a complete path.
import os
path = "Data/students.csv"
print(os.path.basename(path))
Output
students.csv
The os.path.dirname() function extracts only the directory portion of a path.
import os
path = "Data/students.csv"
print(os.path.dirname(path))
Output
Data
The os.path.getsize() function returns the size of a file in bytes.
import os
size = os.path.getsize("students.csv")
print(size)
Sample Output
256
The exact size depends on the contents of the file.
import os
if os.path.exists("sales.csv"):
print("Dataset Found")
else:
print("Dataset Not Found")
Output
Dataset Found
import os
path = "students.csv"
print("Exists :", os.path.exists(path))
print("Is File :", os.path.isfile(path))
print("Size :", os.path.getsize(path), "bytes")
Sample Output
Exists : True
Is File : True
Size : 256 bytes
import os
folder = "Reports"
filename = "sales_report.txt"
path = os.path.join(folder, filename)
print(path)
Sample Output
Reports\sales_report.txt
os.path.join() instead of manually adding path separators.os.path.exists() before opening or deleting files.os.path.isfile() and os.path.isdir() to validate paths.| Application | Purpose |
|---|---|
| Data Analytics | Locate datasets before processing. |
| Backup Software | Verify files before copying. |
| Web Applications | Validate uploaded files. |
| Machine Learning | Load training datasets safely. |
| Automation Scripts | Create portable file paths. |
| Desktop Applications | Display file information. |
Consider the following program.
import os
path = os.path.join("Data", "students.csv")
if os.path.exists(path):
print("File Found")
Execution Steps
os module.os.path.join() creates a platform-independent path.os.path.exists() checks whether the file exists.Output
File Found
os.path.join().os.path.isfile() with os.path.isdir().In this section, you learned how to use the os.path module to check whether files and directories exist, verify file types, create portable file paths using os.path.join(), extract file and directory names, and retrieve file sizes. You also explored practical examples, performance tips, execution flow, and common beginner mistakes. In the final section, you will review the complete lesson through a lesson summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on Advanced File Handling, Context Manager & Best Practices.
In this lesson, you learned how to work with file paths, directories, and Python’s powerful os and os.path modules. These modules enable Python programs to interact with the operating system by navigating directories, creating folders, managing files, and retrieving file information.
You began by understanding what file paths are and learned the difference between absolute and relative paths. You also explored directories (folders), imported the os module, displayed the current working directory using os.getcwd(), and changed directories using os.chdir().
Next, you learned how to create, rename, list, and remove directories using functions such as os.mkdir(), os.makedirs(), os.listdir(), os.rename(), os.rmdir(), and os.removedirs().
Finally, you explored the os.path module and learned how to verify file and directory existence, create platform-independent file paths, retrieve file names and directory names, and determine file sizes. These functions help create reliable and portable Python applications that work across Windows, Linux, and macOS.
Understanding these concepts is essential for automation, data analytics, machine learning, web development, backup software, and system administration.
os module allows interaction with the operating system.os.getcwd() to display the current working directory.os.chdir() to change the current directory.os.mkdir() and os.makedirs() to create directories.os.listdir() to list files and folders.os.path.join() to create portable file paths.os.path.exists() before performing file operations.os.path.isfile() and os.path.isdir() to validate paths.A file path is the complete location of a file or directory on a storage device.
An absolute path starts from the root directory, while a relative path starts from the current working directory.
The built-in os module.
os.getcwd() do?It returns the current working directory.
os.chdir() do?It changes the current working directory.
os.mkdir().
os.listdir().
os.path.join() be used?It creates platform-independent file paths using the correct separator for the operating system.
Use os.path.exists().
Use os.path.getsize().
os.getcwd().os.chdir().Projects.os.makedirs().os.rename().os.path.exists().os.path.join().os.path.getsize().os module?os.getcwd().os.chdir() work?os.mkdir() and os.makedirs()?os.listdir().os.path.join() be preferred over manually joining paths?Create a Python application that performs common file and directory management tasks.
Your program should:
os.path.join().try and except.========== PYTHON FILE MANAGER ==========
Current Directory
C:\Users\Rahul\Projects
----------------------------------------
Project Folder Created
Reports Folder Created
Images Folder Created
----------------------------------------
Directory Contents
Reports
Images
main.py
students.csv
----------------------------------------
Checking File
students.csv Found
File Size : 256 bytes
========================================
Congratulations! You have completed the lesson on Python File Paths, Directories, and the OS Module. You can now navigate directories, manage folders, create platform-independent file paths, and retrieve file information using Python’s built-in modules.
In the next lesson, you will learn Advanced File Handling, Context Manager & Best Practices: Complete Guide for Beginners. You will explore the with statement (Context Manager), automatic file closing, exception handling during file operations, efficient resource management, and professional best practices for writing reliable and maintainable Python applications.