【问题标题】:Converting ascii file to netcdf using python使用python将ascii文件转换为netcdf
【发布时间】:2021-05-23 23:58:08
【问题描述】:

我想将 ascii 文件中的所有数据添加到 netcdf 文件中。 ascii 文件包含地球上每个 0.25 度单元的数据。

我能够创建所有纬度/经度维度,但无法添加数据。 ascii 文件在这里: https://www.dropbox.com/s/lybu6yvm4ph7pcr/tmp.txt?dl=0

有人可以诊断代码并查看问题所在吗?

from netCDF4 import Dataset
import numpy, os, pdb, errno, sys

NUM_LATS = 180.0
NUM_LONS = 360.0

inp_dir  = 'C:\\Input\\'
out_dir  = 'C:\\Output\\nc\\'

def make_dir_if_missing(d):
    try:
        os.makedirs(d)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

make_dir_if_missing(out_dir)

# Read ASCII File
fl_name  = inp_dir+'tmp.txt'
ascii_fl = numpy.loadtxt(fl_name, delimiter=' ')

# Compute dimensions of nc file based on # rows/cols in ascii file
fl_res   = NUM_LATS/ascii_fl.shape[0]
if fl_res != NUM_LONS/ascii_fl.shape[1]:
    print 'Incorrect dimensions in ascii file'
    sys.exit(0)

# Initialize nc file
out_nc   = out_dir+os.path.basename(inp_dir+'tmp.txt')[:-4]+'.nc'
nc_data  = Dataset(out_nc, 'w', format='NETCDF4')
nc_data.description = 'Test'

# dimensions
nc_data.createDimension('lat', ascii_fl.shape[0])
nc_data.createDimension('lon', ascii_fl.shape[1])
nc_data.createDimension('data', 1)

# Populate and output nc file
# variables
latitudes  = nc_data.createVariable('latitude', 'f4', ('lat',))
longitudes = nc_data.createVariable('longitude', 'f4', ('lon',))
glm_data   = nc_data.createVariable('glm_data', 'f4', ('lat', 'lon', 'data'), fill_value=-9999.0)

glm_data.units = ''

# set the variables we know first
latitudes  = numpy.arange(-90.5, 89.5, fl_res)
longitudes = numpy.arange(0.5, 360.5, fl_res)
glm_data   = ascii_fl  ### THIS LINE IS NOT WORKING!!!!!!!


nc_data.close()

【问题讨论】:

    标签: python netcdf


    【解决方案1】:

    你只需要明确写出变量glm_data的二维:

    glm_data[:,:] = ascii_fl[:,:]
    

    【讨论】:

    • 奇怪,我这边没问题。什么不适合你?
    • 嗯,你可以尝试在 Panoply 中打开它吗?
    • 是的,我可以查看数据。如果你使用ncdump之类的东西,你能看到数据被写入文件了吗?
    猜你喜欢
    • 2016-05-18
    • 2018-05-10
    • 2017-11-05
    • 2019-09-20
    • 2018-12-24
    • 2021-06-02
    • 2013-06-28
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多