File I/O
In Python, you can read and write data to and from files. This is known as file I/O (input/output).
Reading and Writing Text Files
To read or write a text file, first open the file using the 'open()' function. Then, use the appropriate file methods, such as 'read()', 'write()', or 'readlines()'. Always close the file after you’re done using it with the close() method.
Example:
# Writing to a file
with open('file.txt', 'w') as f:
f.write('Hello, World!')
# Reading from a file
with open('file.txt', 'r') as f:
content = f.read()
print(content)
Reading and Writing Binary Files
To read or write binary files, such as images or executable files, use the open() function with the mode set to 'rb' (read binary) or 'wb' (write binary).
Example:
# Copying an image file
with open('source.jpg', 'rb') as src, open('destination.jpg', 'wb') as dest:
dest.write(src.read())
Exception Handling
Exceptions are errors that occur during the execution of a program. To handle exceptions, use the 'try', 'except', and 'finally' keywords.
Example:
try:
with open('file.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("The file was not found.")
finally:
print("End of file processing.")
Raising Exceptions
You can raise your own exceptions using the 'raise' keyword or assert a condition using the 'assert' keyword.
Example:
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero.")
return x / y
try:
result = divide(10, 0)
except ValueError as e:
print(e)
Hands-on Exercises
- Write a Python script that reads a text file and counts the number of lines.
- Create a Python script that reads a CSV file and prints the content in a readable format.
- Write a Python script that handles division by zero using exception handling.
Real-World Example
Suppose you’re creating a script that processes user data from a CSV file. You can use Python’s file I/O and exception handling features to read the file, handle any exceptions (such as a missing file or incorrect data format), and process the data.
Additional Resources
- Python documentation: https://docs.python.org/3/tutorial/inputoutput.html
- Real Python: https://realpython.com/read-write-files-python/
- W3Schools Python tutorial: https://www.w3schools.com/python/python_file_handling.asp
Summary and Next Steps
In this lesson, you have learned about:
- File I/O in Python
- Reading and writing text files
- Reading and writing binary files
- Exception handling and raising exceptions
In the next lesson, you will learn about basic data structures in Python, including lists, tuples, sets, and dictionaries. These structures will help you manage and manipulate data more effectively in your programs.
Remember to review the material periodically and practice your skills to reinforce your learning. Good luck on your journey to becoming a Python developer!
Review Questions
- What is the purpose of the
'open()'function in Python? - How do you read and write text files in Python?
- Explain the difference between
'r','w','a','rb', and'wb'modes when opening a file. - What are the keywords used for exception handling in Python?
- Write a Python script that reads a text file and calculates the frequency of each word in the file.



