Chapter 6: File Handling and Exceptions
6.1 Introduction to
File Handling 6.1.1 Opening and closing files Explanation: File handling allows
you to work with external files. You can open a file using the open() function,
perform operations on it, and close it using the close() method. Example:
python
///Example
file =
open("example.txt", "r")
# Opening a file in read mode
content =
file.read() # Reading the file content
print(content)
file.close() # Closing the file
6.1.2 File modes: read,
write, append Explanation: Files can be opened in different modes.
"r" mode is for reading, "w" mode is for writing
(overwriting existing content), and "a" mode is for appending (adding
to existing content). Example:
python
///Example
file = open("example.txt",
"w") # Opening a file in write
mode
file.write("Hello,
World!") # Writing content to the
file
file.close()
6.1.3 File paths and
directories Explanation: File paths specify the location of a file on the
system. You can work with files in different directories by providing the
appropriate file path. Example:
python
///Example
file =
open("path/to/file.txt", "r") # Opening a file with a specific path
content = file.read()
print(content)
file.close()
6.2 Exception Handling
6.2.1 Handling exceptions with try-except Explanation: Exception handling
allows you to catch and handle errors that occur during program execution. The
try-except block is used to catch and handle specific exceptions. Example:
python
///Example
try:
num = int(input("Enter a number:
"))
result = 10 / num
print("Result:", result)
except ValueError:
print("Error: Invalid input. Please
enter a valid number.")
except
ZeroDivisionError:
print("Error: Cannot divide by
zero.")
6.2.2 Handling multiple
exceptions and the else clause Explanation: You can handle multiple exceptions
by using multiple except blocks. The else clause is executed if no exception
occurs. Example:
python
///Example
try:
num = int(input("Enter a number:
"))
result = 10 / num
except ValueError:
print("Error: Invalid input. Please
enter a valid number.")
except
ZeroDivisionError:
print("Error: Cannot divide by
zero.")
else:
print("Result:", result)
6.2.3 The finally
clause and resource cleanup Explanation: The finally clause is used to define
code that must be executed regardless of whether an exception occurs. It is
commonly used for resource cleanup. Example:
python
///Example
try:
file = open("example.txt",
"r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close() # File is closed even if an exception occurs
This chapter covers
file handling and exception handling in Python. File handling allows you to
read from and write to external files, while exception handling enables
graceful error handling. The examples provided demonstrate the usage and syntax
of each topic, helping readers understand how to apply these concepts in their
own programs.
0 comments:
Post a Comment