open_file#

open_file(path_arg, mode='r')[源代码]#

确保文件的打开和关闭干净。

参数
path_arg字符串或整型

作为路径的参数的名称或索引。

mode应力

表示打开模式的字符串。

返回
_open_file功能

干净地执行io的函数。

笔记

注意,当路径参数被指定为字符串时,这个修饰符解决了这个问题,但是当函数想要接受缺省值NONE(然后处理它)时,它不处理这种情况。

以下是如何处理这种情况的示例:

@open_file("path")
def some_function(arg1, arg2, path=None):
   if path is None:
       fobj = tempfile.NamedTemporaryFile(delete=False)
   else:
       # `path` could have been a string or file object or something
       # similar. In any event, the decorator has given us a file object
       # and it will close it for us, if it should.
       fobj = path

   try:
       fobj.write("blah")
   finally:
       if path is None:
           fobj.close()

通常,我们会使用“with”来确保关闭fobj。然而,装饰者会让 path 用户的文件对象,并且使用“with”将不希望关闭该文件对象。相反,我们使用一个try块,如上所示。当我们退出函数时,装饰者将关闭fobj(如果应该关闭的话)。

实例

这样的装饰功能:

@open_file(0,"r")
def read_function(pathname):
    pass

@open_file(1,"w")
def write_function(G, pathname):
    pass

@open_file(1,"w")
def write_function(G, pathname="graph.dot"):
    pass

@open_file("pathname","w")
def write_function(G, pathname="graph.dot"):
    pass

@open_file("path", "w+")
def another_function(arg, **kwargs):
    path = kwargs["path"]
    pass