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 provides several modes for opening a file:
| Mode | Description |
|---|---|
"r"
|
Read - Default value. Opens a file for reading, error if the file does not exist |
"a"
|
Append - Opens a file for appending, creates the file if it does not exist |
"w"
|
Write - Opens a file for writing, creates the file if it does not exist |
"x"
|
Create - Creates the specified file, returns an error if the file exists |
"t"
|
Text - Default value. Text mode |
"b"
|
Binary - Binary mode (e.g. images) |
Example: Binary Modes
Opening a File for Reading
Example: Default Read Mode
This works because the default mode is "rt" (Read Text).
Equivalent Code
Example: Reading File Content
Note: Always remember to close the file after finishing operations.
Example: Using with Statement
Note: This approach is cleaner and safer, as it automatically closes the file even if an error occurs.
