Chapter 5: File Handling and Exceptions in Python

Don't forget to explore our basket section filled with 15000+ objective type questions.

File handling and exceptions are essential aspects of programming that allow you to work with files, read and write data, and handle errors gracefully. In Python, file handling refers to the process of manipulating files stored on the system, while exceptions are mechanisms to catch and handle errors that may occur during program execution. This chapter explores file handling, including opening, reading, writing, and closing files, as well as understanding exceptions and how to handle them effectively.

File Handling Basics

In Python, file handling involves several steps: opening a file, performing operations (reading or writing), and closing the file. Files can be opened in different modes, such as read mode, write mode, append mode, and more. The open() function is used to open files and returns a file object, which is used to interact with the file. Here's an example of opening and closing a file:

file = open("sample.txt", "r")
# Perform operations
file.close()

The "r" parameter in the open() function specifies the read mode, which allows you to read data from the file. Other modes include "w" for write mode and "a" for append mode. The default mode is read mode if no mode is specified.

Reading from Files

Once a file is opened in read mode, you can read its contents using various methods provided by the file object. The most common methods are read(), readline(), and readlines(). The read() method reads the entire content of the file as a single string. The readline() method reads one line at a time, and the readlines() method reads all lines and returns them as a list. Here's an example:

file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()

This code snippet reads the content of the file sample.txt and prints it to the console. Remember to close the file after reading to free system resources.

Writing to Files

To write data to a file, open it in write mode ("w") or append mode ("a"). Write mode creates a new file or overwrites the existing file, while append mode appends data to the existing file. To write data, use the write() method of the file object. Here's an example:

file = open("output.txt", "w")
file.write("Hello, world!")
file.close()

This code snippet creates a new file named output.txt and writes the string "Hello, world!" to it. If the file already exists, its contents will be overwritten.

Exception Handling

Exceptions are errors that occur during program execution and disrupt the normal flow of the program. Python provides a robust exception handling mechanism to catch and handle these errors gracefully. The try-except block is used to catch and handle exceptions. Inside the try block, you write the code that may potentially raise an exception. If an exception occurs, it is caught in the except block, where you can specify the type of exception to handle and define the appropriate response. Here's an example:

try:
    # Code that may raise an exception
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
except ValueError:
    print("Error: Invalid input!")

In this example, the user is prompted to enter two numbers. If the user enters an invalid input (such as a non-numeric value) or attempts to divide by zero, the corresponding exception is caught and an appropriate error message is displayed.

The finally Block

The try-except block can be extended with a finally block, which is executed regardless of whether an exception occurs or not. The finally block is useful for performing cleanup operations, such as closing files or releasing resources, that should be executed regardless of the outcome of the code in the try block. Here's an example:

file = None
try:
    file = open("sample.txt", "r")
    # Perform operations
finally:
    if file:
        file.close()

In this example, the finally block ensures that the file is closed, even if an exception occurs while performing operations on the file.

Handling Multiple Exceptions

You can handle multiple exceptions in a single except block by specifying the exception types separated by commas. This allows you to define a common response for multiple types of exceptions. Here's an example:

try:
    # Code that may raise an exception
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)
except (ZeroDivisionError, ValueError):
    print("Error: Invalid input or division by zero!")

In this example, both ZeroDivisionError and ValueError exceptions are caught in a single except block, and the same error message is displayed for both types of exceptions.

Conclusion

This chapter explored file handling and exceptions in Python. File handling allows you to open, read, write, and close files, enabling you to interact with external data sources. Exceptions help in gracefully handling errors that may occur during program execution. By understanding file handling and exception handling, you can effectively work with files and ensure the stability and robustness of your programs. In the next chapter, we will delve into object-oriented programming (OOP) concepts, including classes, objects, inheritance, and polymorphism.

If you liked the article, please explore our basket section filled with 15000+ objective type questions.