【问题标题】:How to make sure a netcdf file is closed in python?如何确保在 python 中关闭 netcdf 文件?
【发布时间】:2015-08-23 10:22:11
【问题描述】:

这可能很简单,但我一直无法在网上找到解决方案... 我正在尝试使用存储为 netcdf 文件的一系列数据集。我打开每个文件,读入一些关键点,然后转到下一个文件。我发现我经常遇到 mmap 错误/脚本随着更多文件被读入而变慢。我相信这可能是因为 .close() 命令没有正确关闭 netcdf 文件。

我一直在测试这个:

from scipy.io.netcdf import netcdf_file as ncfile
f=ncfile(netcdf_file,mode='r')
f.close()

如果我尝试

>>>f
<scipy.io.netcdf.netcdf_file object at 0x24d29e10>

>>>f.variables['temperature'][:]
array([ 1234.68034431,  1387.43136567,  1528.35794546, ...,  3393.91061952,
    3378.2844357 ,  3433.06715226])

所以看起来文件仍然打开? close() 实际上做了什么?我怎么知道它有效? 有没有办法从 python 关闭/清除所有打开的文件?

软件: Python 2.7.6、scipy 0.13.2、netcdf 4.0.1

【问题讨论】:

    标签: python netcdf


    【解决方案1】:

    f.close 的代码是:

    Definition: f.close(self)
    Source:
        def close(self):
            """Closes the NetCDF file."""
            if not self.fp.closed:
                try:
                    self.flush()
                finally:
                    self.fp.close()
    

    f.fp 是文件对象。所以

    In [451]: f.fp
    Out[451]: <open file 'test.cdf', mode 'wb' at 0x939df40>
    
    In [452]: f.close()
    
    In [453]: f.fp
    Out[453]: <closed file 'test.cdf', mode 'wb' at 0x939df40>
    

    但我从玩f 中看到,我仍然可以创建维度和变量。但是f.flush() 返回错误。

    它看起来不像在数据写入期间使用mmap,只是在读取期间使用。

    def _read_var_array(self):
                ....
                if self.use_mmap:
                    mm = mmap(self.fp.fileno(), begin_+a_size, access=ACCESS_READ)
                    data = ndarray.__new__(ndarray, shape, dtype=dtype_,
                            buffer=mm, offset=begin_, order=0)
                else:
                    pos = self.fp.tell()
                    self.fp.seek(begin_)
                    data = fromstring(self.fp.read(a_size), dtype=dtype_)
                    data.shape = shape
                    self.fp.seek(pos)
    

    我对@9​​87654329@ 没有太多经验。看起来它基于文件中的一个字节块设置了一个mmap 对象,并将其用作变量的数据缓冲区。如果基础文件关闭,我不知道该访问会发生什么。如果出现某种mmap 错误,我不会感到惊讶。

    如果使用mmap=False 打开文件,则将整个变量读入内存,并像常规的numpy 数组一样访问。

    mmap : None or bool, optional
        Whether to mmap `filename` when reading.  Default is True
        when `filename` is a file name, False when `filename` is a
        file-like object
    

    我的猜测是,如果您在未指定 mmap 模式的情况下打开文件,从中读取一个变量,然后关闭该文件,那么以后引用该变量及其数据是不安全的。任何需要加载更多数据的引用都可能导致mmap 错误。

    但是如果你用mmap=False打开文件,你应该可以在关闭文件后切片变量。

    我看不出一个文件或变量的mmap 会如何干扰对其他文件和变量的访问。但我必须在mmap 上阅读更多内容才能确定这一点。

    来自netcdf 文档:

    请注意,当 netcdf_file 用于打开 mmap=True 的文件(默认为只读)时,它返回的数组直接引用磁盘上的数据。该文件不应关闭,并且在询问此类数组是否存在时不能干净地关闭。如果要在关闭文件后处理从 mmapped Netcdf 文件中获取的数据数组,您可能需要复制它们,请参见下面的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-10
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2012-05-18
      • 1970-01-01
      • 2016-03-25
      相关资源
      最近更新 更多