Python 4: Working with File Paths and Changing Directories

🎯 Goal:

By the end of this blog, you’ll be able to:

  • Check and change your current working directory
  • Save files to a custom folder like OneDrive
  • Build platform-safe file paths (Windows or Mac)

📍 1. What is a Working Directory?

When you run a Python script or a notebook, Python has a “default folder” it operates in — this is called the working directory. Any file you read/write (like notes.txt) goes here unless you tell it otherwise.

Check it with:

import os
print(os.getcwd())

🧠 This will tell you where Python is currently reading or writing files from.


🔄 2. Changing the Directory

Let’s say you want to save your file inside a folder called PythonProjects inside your OneDrive.

🪟 On Windows:

import os

# Use raw string (r"...") to avoid errors with backslashes
onedrive_path = r"C:\Users\Prince\OneDrive\PythonProjects"
os.chdir(onedrive_path)
print("Now working in:", os.getcwd())

🍎 On Mac (if using OneDrive):

import os

onedrive_path = "/Users/princejohn/OneDrive/PythonProjects"
os.chdir(onedrive_path)
print("Now working in:", os.getcwd())

📄 3. Creating the Folder (If It Doesn’t Exist)

Just in case the folder doesn’t exist yet:

os.makedirs(onedrive_path, exist_ok=True)
os.chdir(onedrive_path)

🔐 exist_ok=True prevents Python from throwing an error if the folder is already there.


💾 4. Writing a File into OneDrive

Once your working directory is changed:

with open("notes.txt", "w") as file:
    file.write("Saved into OneDrive successfully!")

Now open your OneDrive and you’ll see notes.txt inside the PythonProjects folder.


🔧 5. Building Paths the Safe Way

Instead of manually typing slashes, use os.path.join() — it’s safer across Windows, Mac, and Linux.

filename = "notes.txt"
path = os.path.join(onedrive_path, filename)

with open(path, "w") as file:
    file.write("Cross-platform file writing!")

✅ Summary

  • Use os.getcwd() to see where you’re working
  • Use os.chdir() to move to folders like OneDrive
  • Use os.makedirs() to create folders safely
  • Use os.path.join() to write platform-friendly code

Comments

Leave a comment