File Paths and Folders
File Paths and Folders
Files are stored inside folders.
To work with files well, you need to know where they are saved and how folders are organized.
Python can do this using the os module.
What Is the os Module?
os is a built-in Python module for working with:
- folders
- file paths
- file names
- your current location
- creating folders
- renaming files
Import the os Module
import os
Current Folder
Use os.getcwd().
It shows the folder where your program is running.
import os
print(os.getcwd())
Example Output
/Users/student/projects
List Files and Folders
Use os.listdir().
import os
print(os.listdir())
Example Output
['notes.txt', 'data.csv', 'images']
Create a Folder
Use os.mkdir().
import os
os.mkdir("reports")
This creates a new folder named reports.
Rename a File or Folder
Use os.rename().
import os
os.rename("notes.txt", "tasks.txt")
Check If File Exists
Use os.path.exists().
import os
print(os.path.exists("notes.txt"))
print(os.path.exists("missing.txt"))
Output
True
False
Join Paths Safely
Use os.path.join().
import os
path = os.path.join("reports", "sales.txt")
print(path)
Example Output
reports/sales.txt
Python uses the correct path style for your system.
Remove an Empty Folder
Use os.rmdir().
import os
os.rmdir("old_folder")
The folder must be empty.
Common Beginner Errors
Folder Already Exists
os.mkdir() will fail if the folder already exists.
Wrong File Name
Check spelling carefully.
Removing Non-Empty Folder
os.rmdir() only removes empty folders.
Code Along
Create a folder named backup.
Then check if it exists.
import os
os.mkdir("backup")
print(os.path.exists("backup"))
Output
True
Mini Challenge
Build a folder helper.
Steps:
- Create a folder named
projects - Create this path:
projects/tasks.txt
- Print all files and folders in the current location
- Check if
projectsexists
Expected output example:
['projects', 'notes.txt']
True
Real World Use Case
Programs use os to organize folders, find files, create reports, rename files, and prepare automation tasks.
Quiz
- What does
os.getcwd()return? - What does
os.listdir()do? - What does
os.mkdir()create? - Why use
os.path.join()?
Assignment
Create a folder named data, then create a path to users.txt inside it and print the path.
Summary
You learned how to use the os module to find folders, list files, create folders, rename items, and work with file paths.