File Handling: Reading and Writing Files in Python
Introduction
Working with files is a fundamental skill in Python programming. Whether you’re reading data from a file or writing data to it, understanding file handling will greatly enhance your ability to manage and manipulate data effectively. In this post, we’ll explore how to read from and write to files in Python using simple language and practical examples.
Reading Files
To read a file in Python, you need to open it first. The open()
function is used for this purpose. Here’s how you can do it:
Example 1: Reading a Text File
Let’s say you have a file named example.txt
with the following content:
Hello, this is a sample file.
It contains multiple lines of text.
Here’s how you can read the content of this file:
# Open the file in read mode
with open('example.txt', 'r') as file:
# Read the content of the file
content = file.read()
# Print the content
print(content)
Example 2: Reading a File Line by Line
Sometimes, you may want to read a file line by line. You can achieve this using a loop:
# Open the file in read mode
with open('example.txt', 'r') as file:
# Iterate over each line in the file
for line in file:
# Print each line
print(line.strip()) # .strip() removes leading and trailing whitespace
Writing Files
Writing to a file in Python is just as straightforward. You use the open()
function with the write mode ('w'
). If the file doesn’t exist, it will be created. If it exists, its content will be overwritten.
Example 3: Writing to a Text File
Here’s an example of writing some text to a file:
# Open the file in write mode
with open('output.txt', 'w') as file:
# Write text to the file
file.write("Hello, this is a new file.\n")
file.write("We are writing some text into it.\n")
# The file is automatically closed when the block ends
Example 4: Appending to a File
If you want to add content to an existing file without overwriting it, you can open the file in append mode ('a'
):
# Open the file in append mode
with open('output.txt', 'a') as file:
# Append text to the file
file.write("Appending a new line.\n")
# The file is automatically closed when the block ends
Practical Example: Logging Data
Let’s create a practical example where we log some data to a file. Imagine you are monitoring temperatures and want to log them.
Example 5: Logging Temperatures
def log_temperature(temperature):
with open('temperature_log.txt', 'a') as file:
file.write(f"{temperature}\n")
# Logging temperatures
log_temperature(22.4)
log_temperature(23.1)
log_temperature(21.8)
In this example, each temperature is appended to temperature_log.txt
, creating a log of temperature readings.
Conclusion
File handling is an essential skill for any Python programmer. Whether you are reading data from a file or writing data to it, understanding the basic operations can help you manage data more effectively. By practicing these examples and experimenting with different modes and methods, you’ll become proficient in handling files in Python.
Feel free to experiment with these examples and incorporate file handling into your own projects!