Python With
## Python3.x Python with keyword in exceptions
[ Python3 Errors and Exceptions](#)
The (#) statement in Python is used for exception handling, encapsulating the tryβ¦exceptβ¦finally coding paradigm and improving usability.
**with** statement makes code clearer and more readable, it simplifies the management of common resources such as file streams.
Using the with keyword when handling file objects is a good practice.
Let's look at the following code examples:
Not using **with**, nor using **tryβ¦exceptβ¦finally**
## Example
file=open('./test_tutorial.txt','w')
file.write('hello world !')
file.close()
If an exception occurs during the write call in the above code, the close method will not be executed, so the resource will continue to be occupied by the program and cannot be released.
> More Python with keyword reference: [
Next, we can use **tryβ¦exceptβ¦finally** to improve the code:
## Example
file=open('./test_tutorial.txt','w')
try:
file.write('hello world')
finally:
file.close()
In the above code, we use try to capture code that may throw exceptions. When an exception occurs, the except code block is executed. The finally code block will be executed regardless of what happens, so the file will be closed and resources will not be occupied due to exceptions.
Using **with** keyword:
## Example
with open('./test_tutorial.txt','w')as file:
file.write('hello world !')
Using the **with** keyword, the system will automatically call the f.close() method. The effect of with is equivalent to try/finally statement.
We can check if the file is closed after executing the with keyword:
## Example
>>>with open('./test_tutorial.txt')as f:
... read_data= f.read()
>>># Check if file is closed
>>> f.closed
True
The with statement implementation is based on context managers.
A context manager is a class that implements __enter__ and __exit__ methods.
Using the with statement ensures that the __exit__ method is called at the end of the nested block.
This concept is similar to the use of try...finally block.
## Example
with open('./test_tutorial.txt','w')as my_file:
my_file.write('hello world!')
The above example writes **hello world!** to the ./test_tutorial.txt file.
The file object implements the __enter__ and __exit__ methods, meaning the file object also implements a context manager. It first calls the __enter__ method, then executes the code in the with statement, and finally calls the __exit__ method. Even if an error occurs, the __exit__ method will be called, which means the file stream will be closed.
### Example
The following Python code is a simple travel plan management tool. It reads the city list from the 5A.txt file and provides the following features:
1. **Read city list**: Read city names starting with numbers from the file and add them to the travel plan list.
2. **Delete cities**: The user can enter the number of cities they don't want to go to and their indices to remove corresponding cities from the plan.
3. **Modify cities**: The user can choose to modify the names of certain cities to update the travel plan.
4. **Generate random travel plan**: Shuffle the city order and display the first five cities as the final travel recommendation.
Each line of the 5A.txt file contains a city name starting with a number:
1. Beijing2. Shanghai3. Guangzhou4. Shenzhen5. Chengdu6. Hangzhou7. Xi'an8. Chongqing9. Nanjing10. Suzhou
## Example
from random import shuffle
try:
with open('5A.txt','r')as fp:
i =[line for line in fp if line.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 line ending newline
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 travel to:')
try:
for _ in range(int(city_num)):
index =int(input('Enter the index of the city you do not want to travel to (first city index is 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 plan:')
try:
for _ in range(int(city_num)):
index =int(input('Enter the index of the city
YouTip