class FileCopy:
def __init__(self, source, target):
self.source = source
self.target = target
def __enter__(self):
self.openFile()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exc_type:', exc_type)
print('exc_val:', exc_val)
print('exc_tb:', exc_tb)
self.closeFile()
def startCopy(self):
while True:
b = self.sf.read(2**12)
if not b:
break
self.tf.write(b)
self.tf.flush()
def openFile(self):
self.sf = open(self.source, 'r+b')
self.tf = open(self.target, 'w+b')
def closeFile(self):
self.sf.close()
self.tf.close()
with FileCopy("./exec20.py", './cp20.py') as f1:
print("拷贝中...")
f1.startCopy()
f2.startCopy()
print("文件拷贝完成")
环境管理器 + with语句(Python)
最新推荐文章于 2025-05-30 14:28:55 发布