举出几个python中with-as语句的例子
时间: 2024-05-05 16:15:06 浏览: 88
python with (as)语句实例详解
1. 读取文件并关闭
```
with open('file.txt', 'r') as f:
content = f.read()
print(content)
```
2. 连接数据库并关闭连接
```
import sqlite3
with sqlite3.connect('example.db') as conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM table')
results = cursor.fetchall()
print(results)
```
3. 使用锁来保护共享资源
```
import threading
lock = threading.Lock()
with lock:
# 临界区域
print('do something')
```
阅读全文