Python File Handling
File handling plays a crucial role in many applications, especially when working with data storage, logs, uploads, or configuration files.
Python provides built-in functions that allow you to create, read, modify, and remove files easily, without needing extra libraries.
Working with Files in Python
The primary function used for file operations in Python is
open(). This
function connects your program to a file and returns a
file object that you can work with.
Basic Syntax
- filename → Name (or path) of the file
- mode → Specifies how the file should be opened
File Open Modes
Python supports several modes to control file behavior:
Text Modes
| Mode | Name | Description |
|---|---|---|
| "r" | Read | Opens a file for reading. Raises an error if the file does not exist. |
| "a" | Append | Adds new content to the end of the file. Creates the file if it doesn’t exist. |
| "w" | Write | Overwrites existing content. Creates the file if it doesn’t exist. |
| "x" | Exclusive create | Creates a new file. Raises an error if the file already exists. |
Text vs Binary Mode
You can also define how the file data should be handled:
- "t" → Text mode (default)
- "b" → Binary mode (used for images, audio, video, etc.)
Example combinations:
-
"rb"→ Read binary -
"wb"→ Write binary
Opening a File for Reading
To open a file in read mode, you only need to provide the filename:
This works because
"r" (read)
and
"t" (text)
are both default values. The above line is exactly equivalent to:
Example: Reading File Content
(Assuming a file named
notes.txt
exists in the same directory)
Always remember to close the file after finishing operations to free system resources and prevent data corruption.
Tip: Using with Statement (Recommended)
The
with
statement automatically closes the file for you, even if an error occurs
while the file is open. This approach is cleaner, safer, and widely used in
professional Python code.
