Opens in a new tab
Lesson 5

File I/O and Exception Handling in Python

File I/O & Exceptions, Python Mastery Program, Stage 1 Python

Written by

Muhammad Atif

Last Updated

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:

Python
# 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:

Python
# 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:

Python
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:

Python
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

  1. Write a Python script that reads a text file and counts the number of lines.
  2. Create a Python script that reads a CSV file and prints the content in a readable format.
  3. 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

  1. Python documentation: https://docs.python.org/3/tutorial/inputoutput.html
  2. Real Python: https://realpython.com/read-write-files-python/
  3. W3Schools Python tutorial: https://www.w3schools.com/python/python_file_handling.asp

Summary and Next Steps

In this lesson, you have learned about:

  1. File I/O in Python
  2. Reading and writing text files
  3. Reading and writing binary files
  4. 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

  1. What is the purpose of the 'open()' function in Python?
  2. How do you read and write text files in Python?
  3. Explain the difference between 'r', 'w', 'a', 'rb', and 'wb' modes when opening a file.
  4. What are the keywords used for exception handling in Python?
  5. Write a Python script that reads a text file and calculates the frequency of each word in the file.

Muhammad Atif

Data Analyst & Web Development Professional | Focused on Machine Learning, SQL and Python

Transitioned from a background in finance to IT, I now focus on data science and web development, with specialties in Machine Learning, SQL, and Python. My articles aim to clarify complex IT concepts, informed by a rich history in analytical thinking and strategy.

You Might Also Like

Browse more topics and insights handpicked just for you. Stay updated and informed with our latest articles and news.