__exit__()
以供以后使用。 __enter__()
方法。我见过其中一个用于zipfile
的用法问题> 我已经检查了zipfile的源代码:
/usr/lib/python2.6/zipfile.py
我不知道__enter__
和__exit__
函数的定义在哪里?
谢谢
答案 0 :(得分:9)
zipfile.ZipFile
不是2.6中的上下文管理器,已在2.7中添加。
答案 1 :(得分:4)
我已将此添加为另一个答案,因为它通常不是初始问题的答案。但是,它可以帮助解决您的问题。
class MyZipFile(zipfile.ZipFile): # Create class based on zipfile.ZipFile
def __init__(file, mode='r'): # Initial part of our module
zipfile.ZipFile.__init__(file, mode) # Create ZipFile object
def __enter__(self): # On entering...
return(self) # Return object created in __init__ part
def __exit__(self, exc_type, exc_val, exc_tb): # On exiting...
self.close() # Use close method of zipfile.ZipFile
用法:
with MyZipFile('new.zip', 'w') as tempzip: # Use content manager of MyZipFile
tempzip.write('sbdtools.py') # Write file to our archive
如果您输入
help(MyZipFile)
你可以看到原始zipfile.ZipFile的所有方法和你自己的方法: init ,输入和退出。如果需要,您可以添加另一个自己的功能。 祝你好运!
答案 2 :(得分:2)
使用对象类创建类的示例:
class ZipExtractor(object): # Create class that can only extract zip files
def __init__(self, path): # Initial part
import zipfile # Import old zipfile
self.Path = path # To make path available to all class
try: open(self.Path, 'rb') # To check whether file exists
except IOError: print('File doesn\'t exist') # Catch error and print it
else: # If file can be opened
with open(self.Path, 'rb') as temp:
self.Header = temp.read(4) # Read first 4 bytes
if self.Header != '\x50\x4B\x03\x04':
print('Your file is not a zip archive!')
else: self.ZipObject = zipfile.ZipFile(self.Path, 'r')
def __enter__(self): # On entering...
return(self) # Return object created in __init__ part
def __exit__(self, exc_type, exc_val, exc_tb): # On exiting...
self.close() # Use close method of our class
def SuperExtract(member=None, path=None):
'''Used to extract files from zip archive. If arg 'member'
was not set, extract all files. If path was set, extract file(s)
to selected folder.'''
print('Extracting ZIP archive %s' % self.Path) # Print path of zip
print('Archive has header %s' % self.Header) # Print header of zip
if filename=None:
self.ZipObject.extractall(path) # Extract all if member was not set
else:
self.ZipObject.extract(mamber, path) # Else extract selected file
def close(self): # To close our file
self.ZipObject.close()
用法:
with ZipExtractor('/path/to/zip') as zfile:
zfile.SuperExtract('file') # Extract file to current dir
zfile.SuperExtract(None, path='/your/folder') # Extract all to selected dir
# another way
zfile = ZipExtractor('/path/to/zip')
zfile.SuperExtract('file')
zfile.close() # Don't forget that line to clear memory
如果你运行'help(ZipExtractor)',你会看到五种方法:
__init__, __enter__, __exit__, close, SuperExtract
我希望我帮助过你。我没有测试它,所以你可能需要改进它。
答案 3 :(得分:0)
cat-plus-plus是对的。但如果你愿意,你可以编写自己的类来添加“遗漏”功能。您需要做的就是在您的类中添加两个函数(基于zipfile):
def __enter__(self):
return(self)
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
那应该够了,AFAIR。