|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
文件对象进行包装,从而确认在删除对象时文件能自动关闭
- class FileObject:
- '''给文件对象进行包装从而确认在删除时文件流关闭'''
- def __init__(self, filename='sample.txt'):
- #读写模式打开一个文件
- self.new_file = open(filename, 'r+')
- def __del__(self):
- self.new_file.close()
- del self.new_file
复制代码
请问如何创建文件对象,这段代码要怎么实现
- class FileObject:
- '''给文件对象进行包装从而确认在删除时文件流关闭'''
- def __init__(self, filename='sample.txt'):
- #读写模式打开一个文件
- self.new_file = open(filename, 'r+')
- def __del__(self):
- self.new_file.close()
- del self.new_file
- fo = FileObject("test.txt")
- fo.new_file.read()
- del fo
复制代码
|
|