【问题标题】:Read multiple csv files and write multiple netCDF files读取多个 csv 文件并写入多个 netCDF 文件
【发布时间】:2015-05-23 07:21:09
【问题描述】:

我有以下 Python 代码非常适合将单个 .csv 文件转换为 netCDF 文件。

但是,我有多个文件 (365),如“TRMM_1998_01_02_newntcl.csv”、“TRMM_1998_01_03_newntcl.csv”......直到“TRMM_1998_12_31_newntcl.csv”。

有人可以帮我编写循环遍历所有 csv 文件并使用此代码创建 365 netCDF 文件吗?

任何帮助表示赞赏。

提前致谢。

import numpy as np

def convert_file(filename):
data = np.loadtxt(fname=filename, delimiter=',')
# filename = "TRMM_{}_{}_{}_newntcl.csv".format(d.year,d.month,d.day)
Lat_data = np.loadtxt('Latitude.csv', delimiter=',')
Lon_data = np.loadtxt('Longitude.csv', delimiter=',')

# create a netcdf Data object

with netCDF4.Dataset('TEST_file.nc', mode="w", format='NETCDF4') as ds:
    # some file-level meta-data attributes:
    ds.Conventions = "CF-1.6" 
    ds.title = 'precipitation'
    ds.institution = 'Institute'
    ds.author = 'Author'

    lat_arr = data[:,0] # the first column 
    lon_arr = data[:,1] # the second column 
    precip_arr = data[:,2] # the third column 

    nlat = lat_arr.reshape( (161, 321) )
    nlon = lon_arr.reshape( (161, 321) )  

    # ds.createDimension('time', 0)
    ds.createDimension('latitude', 161)
    ds.createDimension('longitude', 321)


    precip = ds.createVariable('precip', 'f4', ('latitude', 'longitude'))
    precip[:] = data[:,2]
    ## adds some attributes
    precip.units = 'mm'
    precip.long_name = 'Precipitation'


    lat = ds.createVariable('lat', 'f4', ('latitude'))
    lat[:] = Lat_data[:]
    ## adds some attributes
    lat.units = 'degrees_South'
    lat.long_name = 'Latitude'


    lon = ds.createVariable('lon', 'f4', ('longitude'))
    lon[:] = Lon_data[:]
    ## adds some attributes
    lon.units = 'degrees_East'
    lon.long_name = 'Longitude'    


    print ds


 # print filename

# load the data

path='C:\Users\.spyder2'
os.chdir(path)

d=datetime.date(1998,01,01)
while d.year==1998:
    d+=datetime.timedelta(days=1)
    convert_file("TRMM_{}_{}_{}_newntcl.csv".format(d.year,d.month,d.day))

【问题讨论】:

    标签: python loops csv


    【解决方案1】:

    看起来您可以使用datetime.date 对象循环遍历一年中的所有日子。首先,您应该将您拥有的代码放在一个采用文件名的函数中。然后,您可以创建一个date 对象并在循环中调用该函数:

    import datetime
    d=datetime.date(1998,1,1)
    while d.year==1998:
        d+=datetime.timedelta(days=1)
        convert_file("TRMM_{}_{}_{}_newntcl.csv".format(d.year,d.month,d.day))
    

    【讨论】:

    • 首先,我不知道如何使用上面发布的代码创建函数文件。我对python很陌生。然后,我不知道如何使用上面的代码来调用我创建的那个函数。你能举个例子吗?
    • @user3408139 Here 是在 Python 中定义函数的基础教程。在我的代码中,我使用了该函数,假设它被称为 convert_file 并将要转换的文件的名称作为其唯一参数。
    • 好的。我是否需要将上面的代码保存为一个名为“convert_file”的函数,然后在上面运行您的代码?你是这个意思吗?
    • @user3408139 我不确定您所说的“保存...作为函数”是什么意思。您需要做的是将您编写的代码放入一个名为 convert_file 的函数中,该函数将要转换的文件名作为参数,然后将我的代码放在它后面。
    • @user3408139 你需要缩进函数体。此外,您正在立即将 filename 设置为其他内容。
    【解决方案2】:

    如果我正确阅读了您的问题,在这种情况下使用 os 有一种更简单的方法。您可以只接收文件名并在循环中使用它们:

    import os
    
    main_fp = "C:\\Users\\spyder2" 
    path, dirs, files = os.walk(main_fp).next()
    
    for f_path in files:
    
        data = np.loadtxt(f_path, delimiter=',')
        Lat_data = np.loadtxt('Latitude.csv', delimiter=',') #put lat and long csv's in separate folder, so you don't read them into the loop
        Lon_data = np.loadtxt('Longitude.csv', delimiter=',')
    
        #strip csv extentions
        new_fname = f_path.strip('.csv')
    
    
        with netCDF4.Dataset(new_fname+'.nc', mode="w", format='NETCDF4') as ds:
                # some file-level meta-data attributes:
                ds.Conventions = "CF-1.6" 
                ds.title = 'Non TC precipitation'
                ds.institution = 'AIR-Worldwide'
                ds.author = 'Dr. Dumindu Jayasekera'
    
            lat_arr = data[:,0] # the first column 
            lon_arr = data[:,1] # the second column 
            precip_arr = data[:,2] # the third column 
    
            nlat = lat_arr.reshape( (161, 321) )
            nlon = lon_arr.reshape( (161, 321) )  
    
            ds.createDimension('latitude', 161)
            ds.createDimension('longitude', 321)
    
            precip = ds.createVariable('precip', 'f4', ('latitude', 'longitude'))
            precip[:] = data[:,2]
            ## adds some attributes
            precip.units = 'mm'
            precip.long_name = 'Precipitation'
    
            lat = ds.createVariable('lat', 'f4', ('latitude'))
            lat[:] = Lat_data[:]
            ## adds some attributes
            lat.units = 'degrees_South'
            lat.long_name = 'Latitude'
    
            lon = ds.createVariable('lon', 'f4', ('longitude'))
            lon[:] = Lon_data[:]
            ## adds some attributes
            lon.units = 'degrees_East'
            lon.long_name = 'Longitude'   
    
            print ds
    

    【讨论】:

    • 上述代码中的文件名在哪里输入?我的文件名是:TRMM_1998_01_01_newntcl.csv、TRMM_1998_01_02_newntcl.csv 到 TRMM_1998_02_14_newntcl.csv 在“C:\\Users\\spyder2”指定的路径中。
    • 文件名取自文件夹中的文件。请试验代码;运行第一部分并打印出 f_path,这些是你的文件名。
    • 我运行了前 5 行,并在下面收到此错误。回溯(最后一次调用):文件“”,第 8 行,在 中 data = np.loadtxt(path, delimiter=',') File "C:\Users\I54814 \AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\lib\npyio.py",第 860 行,在 loadtxt 项目中 = [conv(val) for (conv, val) in zip(converters, vals)] ValueError:无法将字符串转换为浮点数:rem *** Spyder 终端历史日志 ***
    • 您已更改变量名,请改用 f_path。就像我说的,用代码做实验,我不经常来这里,所以和你一起检查每一行代码是没有用的,因为你一整年都在这里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2015-06-26
    • 1970-01-01
    • 2015-04-09
    • 2013-11-14
    • 2023-01-10
    相关资源
    最近更新 更多