Hey there! So you want to work with files and folders in Python? Maybe automate some boring stuff? Well, the OS module is going to be your new best friend. Trust me, once you get the hang of it, you’ll wonder how you ever lived without it.
What’s This OS Module Anyway?
Think of the OS module as Python’s way of talking to your computer. Want to create a folder? Move files around? Check if something exists? The OS module has got your back. And the best part? It works the same whether you’re on Windows, Mac, or Linux. Write once, run anywhere!
import os
That’s it. One line and you’re ready to go.
Let’s Start Simple – Working with Folders
Where am I right now?
Ever get lost in your terminal? Yeah, me too. Here’s how to check where you are:
current_dir = os.getcwd()
print(f"I'm currently in: {current_dir}")
Moving around
os.chdir('/path/to/somewhere/else')
Making new folders
# Just one folder
os.mkdir('my_new_folder')
# A whole bunch of nested folders at once
os.makedirs('projects/python/my_app')
That second one is super handy. It creates all the folders in the path if they don’t exist yet.
What’s in this folder?
stuff = os.listdir('.')
for thing in stuff:
print(thing)
Simple, right? This shows everything in your current directory.
Dealing with Files and Paths
Does this thing even exist?
Before you try to open or delete something, you probably want to make sure it’s actually there:
if os.path.exists('important_file.txt'):
print("Phew, it's still there!")
else:
print("Uh oh, where'd it go?")
Is it a file or a folder?
if os.path.isfile('something'):
print("It's a file!")
if os.path.isdir('something'):
print("It's a folder!")
Joining paths the smart way
Here’s a rookie mistake I used to make – hardcoding paths with slashes:
Don't do this!
path = 'folder/subfolder/file.txt' # Breaks on Windows!
# Do this instead:
path = os.path.join('folder', 'subfolder', 'file.txt')
# Works everywhere!
Breaking paths apart
full_path = '/home/user/documents/report.pdf'
directory, filename = os.path.split(full_path)
# directory = '/home/user/documents'
# filename = 'report.pdf'
name, extension = os.path.splitext('report.pdf')
# name = 'report'
# extension = '.pdf'
Moving and Deleting Stuff
Renaming files
os.rename('old_boring_name.txt', 'cool_new_name.txt')
Getting rid of things
# Delete a file
os.remove('bye_bye.txt')
# Delete an empty folder
os.rmdir('empty_folder')
# Delete a whole folder tree (be careful with this one!)
os.removedirs('parent/child/grandchild')
Environment Variables – Super Useful!
Your computer has these things called environment variables. They’re like settings that programs can read:
# Where's my home folder?
home = os.environ.get('HOME')
# What's my PATH?
path = os.environ.get('PATH')
# Set your own variable
os.environ['MY_COOL_VAR'] = 'whatever_value'
Some Real-World Examples
Example 1: Walking through all your files
This is one of my favorites. It lets you go through every file in a directory and all its subdirectories:
import os
def show_all_files(start_path):
for root, dirs, files in os.walk(start_path):
level = root.replace(start_path, '').count(os.sep)
indent = ' ' * 2 * level
print(f"{indent}{os.path.basename(root)}/")
sub_indent = ' ' * 2 * (level + 1)
for file in files:
print(f"{sub_indent}{file}")
show_all_files('.')
Example 2: Organizing a messy downloads folder
We’ve all been there – a downloads folder full of random files. Let’s organize them by file type:
import os
def organize_my_mess(folder):
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
# Skip if it's a folder
if not os.path.isfile(file_path):
continue
# Get the file extension
name, ext = os.path.splitext(filename)
if ext:
# Remove the dot from extension
folder_name = ext[1:]
new_folder = os.path.join(folder, folder_name)
# Create folder if it doesn't exist
if not os.path.exists(new_folder):
os.mkdir(new_folder)
# Move the file
new_location = os.path.join(new_folder, filename)
os.rename(file_path, new_location)
print(f"Moved {filename} to {folder_name}/ folder")
# organize_my_mess('/path/to/downloads')
Example 3: Getting file info
import os
import time
def file_info(filepath):
if not os.path.exists(filepath):
print("File doesn't exist!")
return
stats = os.stat(filepath)
size = stats.st_size
modified = time.ctime(stats.st_mtime)
print(f"File: {filepath}")
print(f"Size: {size} bytes")
print(f"Last modified: {modified}")
file_info('some_file.txt')
Quick Tips I Wish Someone Told Me Earlier
1. Always use os.path.join()
Seriously. Even if you’re only working on one operating system right now, your future self (or your teammates) will thank you.
2. Check before you wreck
Always verify a file or folder exists before trying to do something with it. Trust me, you’ll save yourself a lot of headaches:
if os.path.exists(path):
# Do your thing
else:
print("Oops, that doesn't exist!")
3. Use try-except blocks
Things can go wrong. Permissions issues, files in use, you name it:
try:
os.remove('some_file.txt')
except FileNotFoundError:
print("File wasn't there anyway")
except PermissionError:
print("Don't have permission to delete that")
except Exception as e:
print(f"Something weird happened: {e}")
4. Consider pathlib for newer projects
If you’re using Python 3.4 or newer, check out the pathlib
module. It’s more modern and object-oriented. But the OS module is still super useful, and you’ll see it everywhere in older code.
Wrapping Up
Look, the OS module might seem a bit overwhelming at first, but once you start using it, you’ll realize how powerful it really is. Start small maybe just list some files or check if something exists. Then gradually build up to more complex tasks. I’ve included some of the basic features of the OS module here. It has many extensive capabilities that I can’t cover in a single post, but in general, you can use it to interact deeply with your system.
If you guys explore more, please share it with me. You can even create an OS controller using Python modules.