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
Example
Opening a File for Reading
Example
This works because default mode is "rt"
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.
