File Handling in Python
⏱ Estimated reading time: 3 min
File Handling in Python refers to the process of creating, reading, writing, and managing files using Python programs. It enables permanent data storage, as data stored in variables is temporary (lost when the program ends). Python provides built-in functions and methods to work with different types of files such as text, binary, and CSV files.
Python uses a simple and powerful interface for file operations through the built-in function open().
1. Opening a File
A file is opened using:
Common File Modes
| Mode | Meaning |
|---|---|
'r' | Read (default) |
'w' | Write (overwrites file) |
'a' | Append (adds data to end) |
'b' | Binary mode |
't' | Text mode (default) |
'x' | Create file (error if file exists) |
'r+' | Read and write |
Example:
2. Reading from a File
Python provides several methods to read a file:
a) read()
Reads the entire file content.
b) readline()
Reads one line at a time.
c) readlines()
Reads all lines into a list.
3. Writing to a File
a) write()
b) writelines()
Writes a list of strings.
4. Closing a File
It is important to close a file to free system resources:
5. Using with Statement (Best Method)
Using the with statement automatically closes the file after operations.
Advantages:
-
No need to call
close() -
Automatically handles errors
6. File Handling for Binary Files
Used for images, videos, and audio.
Writing binary files:
7. Important File Methods
| Method | Description |
|---|---|
read() | Reads entire file |
readline() | Reads one line |
readlines() | Reads all lines |
write() | Writes data |
writelines() | Writes list of strings |
seek() | Moves the cursor |
tell() | Returns current cursor position |
close() | Closes file |
Example of seek():
8. Exception Handling in File Operations
File operations may cause errors (e.g., file not found). Use try-except:
9. File Handling Applications
-
Logging
-
Storing user data
-
Reading configuration files
-
Processing big data files
-
Handling CSV files for data analysis
Conclusion
File Handling in Python provides a simple and powerful way to read, write, and manage files. Using the open() function, different modes, built-in methods, and exception handling, Python enables efficient processing of both text and binary files. The with statement makes file handling more reliable and professional. Understanding file handling is essential for real-world applications such as data processing, machine learning, and automation.
Register Now
Share this Post
← Back to Tutorials