Day 6: File Handling: Reading and Writing Files
Welcome to Day 6 of our 90-day journey to learn core Python! Yesterday, we explored data structures, specifically lists and dictionaries. Today, we’ll dive into file handling, a crucial aspect of working with external data. Let’s get started!
Reading Files
Python provides several methods for reading data from files. We can open a file using the open()
function and specify the file path and mode. Let's see an example of reading a text file:
file = open('data.txt', 'r') # Open file in read mode
content = file.read() # Read entire file content
file.close() # Close the file
We can also read the file line by line using the readline()
method or retrieve all lines as a list using the readlines()
method.
Writing Files
To write data to a file, we open it in write mode ('w'
). If the file doesn't exist, Python creates it. Here's an example of writing content to a file:
file = open('output.txt', 'w') # Open file in write mode
file.write('Hello, World!') # Write content to the file
file.close() # Close the file
By default, the write()
method overwrites the existing content. If you want to append new content to an existing file, use the append mode ('a'
) instead.
Context Managers: With Statement
Using context managers with the with
statement is a recommended practice for file handling. It ensures that files are automatically closed, even if an exception occurs. Here's an example:
with open('data.txt', 'r') as file:
content = file.read()
# Process the content
With the with
statement, we don't need to explicitly close the file. It improves code readability and handles file resources efficiently.
Conclusion
Congratulations on completing Day 6 of our Python learning journey! Today, we explored file handling, learning how to read and write data from and to files. This skill is essential for working with external data sources.
Take some time to practice reading and writing files in your code. Tomorrow, on Day 7, we’ll delve into exception handling, enabling us to gracefully handle and recover from errors in our programs.
Keep up the great work, and I’ll see you tomorrow for Day 7! Happy coding! 🚀
Note: This blog post is part of a 90-day series to teach core Python programming from scratch. If you missed any previous days, you can find them in the series index here.