當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python NetworkX open_file用法及代碼示例

本文簡要介紹 networkx.utils.decorators.open_file 的用法。

用法:

open_file(path_arg, mode='r')

裝飾器以確保文件的幹淨打開和關閉。

參數

path_arg字符串或int

作為路徑的參數的名稱或索引。

modestr

打開模式的字符串。

返回

_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

相關用法


注:本文由純淨天空篩選整理自networkx.org大神的英文原創作品 networkx.utils.decorators.open_file。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。