User input filename when reading in netCDF files in Python

336 views Asked by At

I have a set of soil moisture data files from 1953 to 2014. All of them are of the form cpc_soil_YYYY.nc (where YYYY is one of those years). Is there a way for me to ask for user input of which year the user would like to view, and have my program open the corresponding function? I currently have it where I must manually change the year within gedit, and wrote functions to grab each variable (soil moisture as a function of time, lat, lon):

    import netCDF4 as nc
    import numpy as np
    import numpy.ma as ma
    import csv as csv

    fid=nc.MFDataset('/data/reu_data/soil_moisture/cpc_soil_1957.nc','r')
    fid.close()
    ncf='/data/reu_data/soil_moisture/cpc_soil_1957.nc'

    def read_var(ncfile, varname):
        fid=nc.Dataset(ncfile, 'r')
        out=fid.variables[varname][:]   
        fid.close()
        return out

    time=read_var(ncf, 'time')
    lat=read_var(ncf, 'lat')
    lon=read_var(ncf, 'lon')
    soil=read_var(ncf, 'soilw')
1

There are 1 answers

0
ronakg On BEST ANSWER

You can use input() to ask user to enter the year. Then you can use that to generate the filepath.

...
year = input("Enter year: "))
filename = '/data/reu_data/soil_moisture/cpc_soil_%s.nc' % (year,)
fid=nc.MFDataset(filename,'r')
fid.close()
...

You should do error checking to make sure the user entered value is actually a year and falls within the range of your data.

You can read more on input/output in Python here.