Python The with Keyword in Exceptions
The with statement in Python is used for exception handling; it wraps the try...except...finally coding pattern and improves usability.
with The statement makes code clearer and more readable, and simplifies the management of common resources such as file streams.
Using the with keyword when handling file objects is good practice.
Let's look at the following code examples:
does not use with, nor use try…except…finally
Example
file
=
open
(
'./test_runoob.txt'
,
'w'
)
file
.
write
(
'hello world !'
)
file
.
close
(
)
If an exception occurs while calling write in the code above, the close method will not be executed, so the resource will remain occupied by the program and cannot be released.
For more on the Python with keyword, see:https://www.runoob.com/python3/python3-with-keyword.html
Next we can use try…except…finally to improve the code:
Example
file
=
open
(
'./test_runoob.txt'
,
'w'
)
try
:
file
.
write
(
'hello world'
)
finally
:
file
.
close
(
)
In the code above we wrap the code that may raise an exception in try, execute the except block when an exception occurs, and the finally block always executes regardless of circumstances, so the file is closed and no resource is held because of an exception.
Use with keyword:
Example
with
open
(
'./test_runoob.txt'
,
'w'
)
as
file
:
file
.
write
(
'hello world !'
)
Use with The keyword causes the system to call the f.close() method automatically; the effect of with is equivalent to a try/finally statement.
We can check whether the file is closed after executing the with keyword:
Example
with
open
(
'./test_runoob.txt'
)
as
f:
...
read_data
=
f.
read
(
)
Check whether the file is closed
f.
closed
True
The with statement is implemented on top of context managers.
A context manager is a class that implements the enter and exit methods.
Using the with statement ensures that the exit method.
This concept is similar to the use of a try...finally block.
Example
with
open
(
'./test_runoob.txt'
,
'w'
)
as
my_file:
my_file.
write
(
'hello world!'
)
The example above writes hello world! to the ./test_runoob.txt file.
The file object defines the enter and exit methods, meaning the file object also implements a context manager: first the enter method is called, then the code in the with statement executes, and finally the exit method is called. Even if an error occurs, the exit method is called, that is, the file stream is closed.
Example
The following Python code is a simple travel plan management tool. It reads a list of cities from the 5A.txt file and provides the following features:
-
Read the city list: Read city names starting with a number from the file and add them to the travel plan list.
-
Delete cities: The user can enter the number and indices of cities they do not want to visit, and the corresponding cities are removed from the plan.
-
Modify cities: The user can choose to change the names of certain cities, updating the travel plan.
-
Generate a random travel plan: Shuffle the order of the cities and display the first five as the final travel recommendation.
Each line of the 5A.txt file contains a city name starting with a number:
1. 北京
2. 上海
3. 广州
4. 深圳
5. 成都
6. 杭州
7. 西安
8. 重庆
9. 南京
10. 苏州
Example
from
random
import
shuffle
try
:
with
open
(
'5A.txt'
,
'r'
)
as
fp:
i
=
[
line
for
line
in
fp
if
line
[
0
]
.
isdigit
(
)
]
except
FileNotFoundError:
(
"File '5A.txt' not found, please check the file path."
)
exit
(
)
travelList
=
[
]
Add tourist cities
for
index
,
item
in
enumerate
(
i
)
:
temp_1
=
item.
strip
(
)
[
2
:
]
Use strip to remove the trailing newline
temp_1
=
f
"{index}#{temp_1}"
travelList.
append
(
temp_1
)
(
"Travel plan cities:"
,
travelList
)
Delete tourist 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 cities you do not want to visit (the first city has index 0)'
)
)
if
0
<=
index
<
len
(
travelList
)
:
travelList.
pop
(
index
)
(
"Travel plan cities:"
,
travelList
)
else
:
(
"The index entered is out of range."
)
except
ValueError
:
(
"Please enter a valid integer."
)
Modify tourist cities
city_num
=
input
(
'Enter the number of cities to modify:'
)
try
:
for
_
in
range
(
int
(
city_num
)
)
:
index
=
int
(
input
(
'Enter the indices of cities to modify (the first city has index 0)'
)
)
if
0
<=
index
<
len
(
travelList
)
:
city_name
=
input
(
'Enter the new city name:'
)
travelList
[
index
]
=
city_name
(
'Travel plan cities:'
,
travelList
)
else
:
(
"The index entered is out of range."
)
except
ValueError
:
(
"Please enter a valid integer."
)
shuffle
(
travelList
)
(
'Here is your TOPS travel plan:'
,
travelList
[
:
5
]
)
Running the code above 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#. 苏州']
Python3 Errors and Exceptions