"with" keyword in Python Exceptions
In Python, thewithstatement is used for exception handling, encapsulatingtry…except…finallycoding paradigms, improving usability.
withThe statement makes code clearer and more readable, and it simplifies the management of common resources such as file streams.
Using the with keyword when handling file objects is a good practice.
We can take a look at the following code examples:Without usingwith, and without usingtry…except…finally
Example
file.write('hello world !')
file.close()
In the above code, if an exception occurs during the call to write, the close method will not be executed, so the resource will remain occupied by the program and cannot be released.
More references for the Python with keyword:https://www.example.com/python3/python3-with-keyword.html
Next, we can usetry…except…finallyto improve the code:
Example
try:
file.write('hello world')
finally:
file.close()
In the above code, we use try to catch exceptions where they may occur. When an exception occurs, the except block is executed, and the finally block is executed no matter what, so the file will be closed and resources will not be occupied due to exceptions during execution.
Usingwithkeyword:
Example
file.write('hello world !')
Usingwithkeyword, the system will automatically call the f.close() method, and the effect of with is equivalent to the try/finally statement.
We can check whether the file is closed after executing the with keyword:Example
... read_data = f.read()
>>> # Check whether the file is closed
>>> f.closed
True
The implementation principle of the with statement is built on the context manager.
A context manager is a class that implements the__enter__and__exit__method.
Using the with statement ensures that the __exit__ method is called at the end of the nested block.
This concept is similar to using try...finally blocks.
Example
my_file.write('hello world!')
The above example writeshello world!to the ./test_example.txt file.
In the file object, the __enter__ and __exit__ methods are defined, meaning the file object also implements the context manager. First, the __enter__ method is called, then the code in the with statement is executed, and finally the __exit__ method is called. Even if an error occurs, the __exit__ method is still called, which means the file stream will be closed.
Example
The following Python code is a simple travel plan management tool that reads a list of cities from the 5A.txt file and provides the following functions:
Read city list: Read city names starting with a number from the file and add them to the travel plan list.
Delete cities: Users can enter the number and indices of the cities they do not want to visit, and the corresponding cities will be removed from the plan.
Modify cities: Users can choose to modify the names of certain cities to update the travel plan.
Generate random travel plan: Shuffle the city order and display the first five cities as the final travel recommendation.
Each line in the 5A.txt file contains a city name starting with a number:
1. 北京 2. 上海 3. 广州 4. 深圳 5. 成都 6. 杭州 7. 西安 8. 重庆 9. 南京 10. 苏州
Example
try:
with open('5A.txt', 'r') as fp:
i = [line for line in fp if line[0].isdigit()]
except FileNotFoundError:
print("File '5A.txt' not found, please check the file path.")
exit()
travelList = []
# Add travel cities
for index, item in enumerate(i):
temp_1 = item.strip()[2:] # Use strip to remove the newline at the end of the line
temp_1 = f"{index}#{temp_1}"
travelList.append(temp_1)
print("Travel plan cities:", travelList)
# Delete travel cities
city_num = input('Enter the number of cities you do not want to visit:')
try:
for _ in range(int(city_num)):
index = int(input('Enter the indices of the cities you do not want to visit (the first city has index 0)'))
if 0 <= index < len(travelList):
travelList.pop(index)
print("Travel plan cities:", travelList)
else:
print("The entered index is out of range.")
except ValueError:
print("Please enter a valid integer.")
# Modify travel cities
city_num = input('Enter the number of cities to modify in the travel plan:')
try:
for _ in range(int(city_num)):
index = int(input('Enter the indices of the cities to modify in the travel plan (the first city has index 0)'))
if 0 <= index < len(travelList):
city_name = input('Enter the names of the cities to modify in the travel plan:')
travelList[index] = city_name
print('Travel plan cities:', travelList)
else:
print("The entered index is out of range.")
except ValueError:
print("Please enter a valid integer.")
shuffle(travelList)
print('Please claim your TOPS travel plan:', travelList[:5])
Executing the above code produces output similar to the following:
旅游计划城市: ['0# 北京', '1# 上海', '2# 广州', '3# 深圳', '4# 成都', '5# 杭州', '6# 西安', '7# 重庆', '8# 南京', '9#. 苏州'] 输入不想旅游城市的个数:0 输入修改计划旅游的城市个数:3 输入修改计划旅游的城市序号(第1个城市索引为0)4 输入修改计划旅游的城市名称:7 旅游计划城市: ['0# 北京', '1# 上海', '2# 广州', '3# 深圳', '7', '5# 杭州', '6# 西安', '7# 重庆', '8# 南京', '9#. 苏州']Other extensions
Python3 Errors and Exceptions