Python File Handling: Read and Write Files
In this sixth article of our beginner-friendly Python tutorial series, we'll explore Python file handling. Being able to read from and write to files is an essential skill for any programmer, as it enables you to store and retrieve data, share information between programs, and more.
Opening and Closing Files
Before you can read from or write to a file, you need to open it. The built-in `open()` function is used to open a file. The function takes two arguments: the file path and the mode in which to open the file. Some common modes include:
- r: Read mode (default)
- w: Write mode (overwrites the file if it exists)
- a: Append mode (adds data to the end of the file)
- x: Exclusive creation mode (creates a new file, but raises an error if the file already exists)
When you're done working with a file, it's important to close it using the `close()` method. This ensures that resources are released, and any changes to the file are saved.
file = open("example.txt", "r")
# Perform file operations here
file.close()
Reading from a File
1. Reading the Entire File
To read the entire contents of a file, you can use the `read()` method. Here's an example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
2. Reading Line by Line
You can read a file line by line using a for loop or the `readline()` method. Here are examples of both methods:
# Using a for loop
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
# Using the readline() method
file = open("example.txt", "r")
line = file.readline()
while line:
print(line.strip())
line = file.readline()
file.close()
Writing to a File
To write to a file, you can use the `write()` method. Make sure to open the file in write ('w') or append ('a') mode. Here's an example:
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.write("This is a new line.\n")
file.close()
Using the with Statement
It's recommended to use the with statement when working with files, as it automatically takes care of closing the file for you. This helps to prevent resource leaks and ensures that any changes to the file are saved. Here's an example:
with open("example.txt", "r") as file:
content = file.read()
print(content) #The file is automatically closed after the block of code is executed
Working with Binary Files
If you need to work with binary files, such as images or executables, you can open the file in binary mode by adding a 'b' to the mode argument. Here's an example:
# Reading a binary file
with open("example.bin", "rb") as file:
content = file.read()
# Writing a binary file
with open("example.bin", "wb") as file:
file.write(b'\x01\x02\x03\x04\x05')
Now that you've learned the basics of Python file handling, you can read from and write to files in your Python programs. This skill will enable you to store and retrieve data, share information between programs, and more. In the next article, we'll cover error handling in Python, which will help you write more robust and resilient code. Stay tuned!