本文简要介绍
networkx.utils.decorators.open_file
的用法。用法:
open_file(path_arg, mode='r')
装饰器以确保文件的干净打开和关闭。
- path_arg:字符串或int
作为路径的参数的名称或索引。
- mode:str
打开模式的字符串。
- _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
相关用法
- Python NetworkX optimal_edit_paths用法及代码示例
- Python NetworkX optimize_graph_edit_distance用法及代码示例
- Python NetworkX overlap_weighted_projected_graph用法及代码示例
- Python NetworkX negative_edge_cycle用法及代码示例
- Python NetworkX voronoi_cells用法及代码示例
- Python NetworkX numerical_edge_match用法及代码示例
- Python NetworkX inverse_line_graph用法及代码示例
- Python NetworkX LFR_benchmark_graph用法及代码示例
- Python NetworkX write_graph6用法及代码示例
- Python NetworkX DiGraph.__contains__用法及代码示例
- Python NetworkX average_degree_connectivity用法及代码示例
- Python NetworkX eulerian_circuit用法及代码示例
- Python NetworkX single_source_dijkstra_path_length用法及代码示例
- Python NetworkX from_dict_of_dicts用法及代码示例
- Python NetworkX weisfeiler_lehman_subgraph_hashes用法及代码示例
- Python NetworkX transitive_closure_dag用法及代码示例
- Python NetworkX intersection用法及代码示例
- Python NetworkX MultiGraph.size用法及代码示例
- Python NetworkX Graph.size用法及代码示例
- Python NetworkX from_scipy_sparse_array用法及代码示例
- Python NetworkX local_and_global_consistency用法及代码示例
- Python NetworkX number_of_selfloops用法及代码示例
- Python NetworkX single_source_bellman_ford用法及代码示例
- Python NetworkX all_simple_paths用法及代码示例
- Python NetworkX Graph.to_undirected用法及代码示例
注:本文由纯净天空筛选整理自networkx.org大神的英文原创作品 networkx.utils.decorators.open_file。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。