Working with Files and Directories in Python
If you’ve been learning Python for a while, there comes a point where printing to the screen is no longer enough. Real programs need to save data, read existing files, organize content inside folders, and sometimes even move or rename files automatically.
That’s where working with files and directories becomes essential.
In this guide, I’ll walk you through everything in a simple, clear, and practical way — no academic tone, no complicated explanations. Just real understanding with examples you can try yourself.
What Is a File in Python?
A file is simply a sequence of bytes stored on your system. It could be:
-
A
.txttext file -
A
.csvdata file -
A
.jpgimage🖼️ -
Or even a program file
Python lets you read from files and write to them easily using built-in functions.
Opening a File with open()
Before doing anything with a file, you must open it.
There are different modes you can use:
File Modes
| Mode | Meaning |
|---|---|
r | Read (default) |
w | Write (overwrites if file exists) |
a | Append (adds content at the end) |
x | Create file (fails if file exists) |
b | Binary mode |
t | Text mode (default) |
Example:
This creates an empty file if it doesn’t exist.
Writing to a Text File
There are two common ways to write to a file:
1. Using print()
2. Using write()
Important difference:
-
print()automatically adds a newline. -
write()does not.
If you want print() to behave like write():
Reading from a Text File
There are several ways to read a file.
1. read() – Read everything
Be careful with very large files. Reading everything at once can consume a lot of memory.
2. readline() – Read line by line
3. Using a Loop ( I prefer this way)
This is the cleanest method:
This automatically closes the file after finishing. No need to call close() manually.
Why Use with?
When you use:
Python automatically handles closing the file, even if an error happens. This is safer and cleaner.
Always prefer this style.
Working with Binary Files
Binary mode is used for:
-
Images
-
Audio files
-
PDFs
-
Any non-text content
Example of writing binary data:
To read it:
Notice the b in "wb" and "rb".
File Position: tell() and seek()
Python keeps track of where you are in a file.
tell()
Returns current position.
seek(offset, origin)
Moves to another position.
Example:
origin values:
-
0→ From start -
1→ From current position -
2→ From end
This is useful when you need to read specific parts of large files.
Checking If a File Exists
Using os.path:
Other useful checks:
Copying and Renaming Files
Python makes file management simple.
Copy a file
Rename a file
Delete a file
Working with Directories (Folders)
Files usually live inside directories.
Create a directory
Delete a directory
List directory contents
. means current directory.
.. means parent directory.
Changing Directory
This moves your working location into that folder.
Searching Files with glob()
The glob module lets you search using patterns.
Pattern rules:
-
*→ matches everything -
?→ single character -
[abc]→ matches a, b, or c -
[!abc]→ matches anything except a, b, c
Example:
Finds all files starting with “m”.
Building Paths Safely
Instead of manually writing:
Use:
This ensures compatibility across Windows, Linux, and macOS.
Using pathlib (Modern Approach)
Python introduced pathlib to simplify path handling.
Example:
This feels cleaner and more readable.
Final Thoughts
Learning file and directory handling in Python unlocks real programming power. Once you understand how to:
-
Open files
-
Write data
-
Read content safely
-
Manage folders
-
Search and manipulate paths
You move from beginner scripts to real-world applications.
Everything from data analysis to web apps and automation depends on file handling.
Start small. Create a text file. Write to it. Read from it. Then move into directories and file operations. The more you practice, the more natural it becomes.
GOOD LUCK BUDDY (:
Comments
Post a Comment