CodingNic

Files, Errors, and Automation

File Paths and Folders

Files, Errors, and Automation 28 min read

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

python
import os

Current Folder

Use os.getcwd().

It shows the folder where your program is running.

python
import os

print(os.getcwd())

Example Output

text
/Users/student/projects

List Files and Folders

Use os.listdir().

python
import os

print(os.listdir())

Example Output

text
['notes.txt', 'data.csv', 'images']

Create a Folder

Use os.mkdir().

python
import os

os.mkdir("reports")

This creates a new folder named reports.

Rename a File or Folder

Use os.rename().

python
import os

os.rename("notes.txt", "tasks.txt")

Check If File Exists

Use os.path.exists().

python
import os

print(os.path.exists("notes.txt"))
print(os.path.exists("missing.txt"))

Output

text
True
False

Join Paths Safely

Use os.path.join().

python
import os

path = os.path.join("reports", "sales.txt")
print(path)

Example Output

text
reports/sales.txt

Python uses the correct path style for your system.

Remove an Empty Folder

Use os.rmdir().

python
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.

python
import os

os.mkdir("backup")
print(os.path.exists("backup"))

Output

text
True

Mini Challenge

Build a folder helper.

Steps:

  • Create a folder named projects
  • Create this path:
text
projects/tasks.txt
  • Print all files and folders in the current location
  • Check if projects exists

Expected output example:

text
['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

  1. What does os.getcwd() return?
  2. What does os.listdir() do?
  3. What does os.mkdir() create?
  4. 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.