for x in range(10000000):
f = open('test.txt','w')
f.write('test file')
报错:
for x in range(10000000):
with open('test.txt','w'):
f.write('test file')
也可以用try except finally语句处理
f = open('test.txt','w')
try:
f.write('hello')
finally:
f.close()
1、打开、关闭文件操作
class FileManager:
def __inin__(self,name,mode):
self.name = name
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.name,self.mode)
return self.file
def __exit__(self,exc_type,exc_val,exc_tb):
if self.file:
self.file.close()
with FileManager('test.txt','w') as f:
f.write('hello world')
就和我们使用with open() as f一样
需要注意的是,当使用类来创建上下文管理器时,必须保证类包括’__ enter__’ 和 ’__ exit__'方法
2、打开、关闭数据库操作
class MysqlDbManager:
def __init__(self,host,port,user,password,database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
def __enter__(self):
self.conn = pymysql.connnect(
host = self.host,
port = self.port,
user = self.user,
password = self.password,
database = self.database
)
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()