代码之家  ›  专栏  ›  技术社区  ›  Oalvinegro

在gz文件中打开netcdfs数据

  •  0
  • Oalvinegro  · 技术社区  · 1 年前

    我已将netcdfs保存在 gz file 我正试图在python上作为地理数据框架导入。我不知道netcdfs中变量的名称。

    我的代码:

    
    gzipped_file_path = 'Maize_1970_Yield_ver12b_BRA.nc.gz'
    
    
    with gzip.open(gzipped_file_path, 'rb') as f:
        # Read the content of the gzipped file
        content = f.read()
    
    

    这部分工作得很好,但在尝试创建数据集时,我正在尝试:

    df=nc.Dataset(content)
    

    它开始永远运行(截至目前已经运行了3个多小时)。 这个代码出了什么问题?

    1 回复  |  直到 1 年前
        1
  •  1
  •   Dimitar    1 年前

    好吧,所以 nc.Database 函数希望为打开的文件获取文件名或文件ID。

    因此,首先,让我们准备好打开文件:

    import gzip, os
    import netCDF4 as nc
    
    gzipped_file_path = 'Maize_1970_Yield_ver12b_BRA.nc.gz'
    temp_nc_path = 'temp_netcdf_file.nc'
    
    with gzip.open(gzipped_file_path, 'rb') as f_in, open(temp_nc_path, 'wb') as f_out:
        f_out.write(f_in.read())
    

    现在 f_out 是一个打开的文件,基本上包含 f_in ,您可以使用 nc数据库 功能:

    ds = nc.Dataset(temp_nc_path)
    print(ds.variables.keys()) # check the keys
    

    最后,关闭文件并删除临时文件,以避免系统中的垃圾和必须对 tmp 稍后的文件夹:

    ds.close()
    os.remove(temp_nc_path)
    

    这样就可以了。