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")
file.close()
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()
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.
with open("data.bin", "wb") as file:
file.write(b"Python Bytes")
with open("data.bin", "rb") as file:
content = file.read()
print(content)
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.
In the next article, we'll explore Object-Oriented Programming (OOP) in Python — classes, objects, and everything that makes Python truly powerful.
Comments
No comments yet. Ask a question or share what helped.