File handling is one of the most important aspects of programming. It allows you to store, retrieve, and manage data permanently. In Python, you can easily read and write both text and binary files using built-in functions and context managers.
Opening and Closing Files
Python provides the open() function to interact with files.
file = open("filename", "mode")
# Perform operations
file.close()
| Mode |
Description |
| 'r' |
Read mode (default). File must exist. |
| 'w' |
Write mode. Overwrites existing content or creates a new file. |
| 'a' |
Append mode. Adds new data to the end of the file. |
| 'b' |
Binary mode (used with โrโ, โwโ, or โaโ). |
| 't' |
Text mode (default). |
Example:
file = open("sample.txt", "w")
file.write("Hello, Python!")
file.close()
This creates (or overwrites) sample.txt and writes "Hello, Python!" to it.
Reading Files
Once a file is opened in read mode, you can use various methods to access its content.
file = open("sample.txt", "r")
data = file.read()
print(data)
file.close()
| Method |
Description |
| read() |
Reads the entire file as a string |
| readline() |
Reads one line at a time |
| readlines() |
Returns all lines as a list |
Example:
file = open("data.txt", "r")
for line in file:
print(line.strip())
file.close()
Writing to Files
Use the write() or writelines() methods to write data to a file.
file = open("output.txt", "w")
file.write("Python makes file handling easy!\n")
file.writelines(["You can write multiple lines at once.\n", "Just use writelines method.\n"])
file.close()
When you use 'w' mode, existing file data will be erased.
Working with Binary Files
Binary files store data in bytes rather than text. Use 'rb' and 'wb' modes for binary operations.
# Writing binary data
with open("data.bin", "wb") as file:
file.write(b"Python Bytes")
# Reading binary data
with open("data.bin", "rb") as file:
content = file.read()
print(content) # b'Python Bytes'
Using Context Managers (with statement)
The with statement automatically handles opening and closing files โ even if an error occurs.
This is the recommended way to manage files.
with open("sample.txt", "r") as file:
data = file.read()
print(data)
No need to call close() โ Python closes the file automatically. Prevents resource leaks and improves code readability.
Example: Reading and Writing Together
with open("input.txt", "r") as infile:
content = infile.read()
with open("copy.txt", "w") as outfile:
outfile.write(content)
print("File copied successfully!")
This script reads data from input.txt and writes it into copy.txt โ a simple file copy program.
Summary
File handling in Python provides a simple yet powerful way to work with data โ from text logs to large binary files. Using with statements ensures safe file operations and cleaner code.
| Concept |
Description |
| open() |
Opens a file in the specified mode |
| read(), readline(), readlines() |
Reads file data |
| write(), writelines() |
Writes data to a file |
| 'r', 'w', 'a', 'b', 't' |
File access modes |
| with statement |
Automatically manages file resources |
| Binary files |
Used for non-text data (images, audio, etc.) |
In the next article, we'll explore Object-Oriented Programming (OOP) in Python โ classes, objects, and everything that makes Python truly powerful.