Search code examples
pythongdal

How to extract the name of inputfile for the outputfile when using python?


I have several (daily) Netcdf files in one folder: for 5 years 2010 and 2015

I want to extract some variables from these files using gdal_translate but I have a problem with how to represent the date written in the Netcdf file in my code.

The files are named like this:

Nx.20120329.SUB.nc

The code:

 import os
 for year in range (2010,2014):
  yearp=str(year).zfill(2)

    for month in range(1,13):
     monthp=str(month).zfill(2)
for doy in range (1, 32):
        doy=str(doy).zfill(2)
        inputFile='C:\\Users\\Nx.'+str(year)+''+monthp+''+str(doy)+'.SUB.nc'
        inputDataset='NETCDF:\"'+inputFile+'\":sf'

        outputFile='C:\\Users\\Nx.'+str(year)+''+monthp+''+str(doy)+'.SUB.img'
        gdalcmd='gdal_translate -of "ENVI" '+inputDataset+' '+outputFile
           os.system( gdalcmd)

My question: is there a way to just give the output file the same name as the inputfile so I do not need to precise from this year to that or from this month to that etc. take all files in any specified folder, extract the variable needed and put the exact name of the inputfile? No matter how many files or years in your folder?


Solution

  • You can specify starting directory and based on the extension process all the file in it, here is what I would do...

    import os
    import fnmatch
    
    filenamels = []
    inputExtension = ".nc"
    outputExtension = ".img"
    inputDir = "C:\\Users\\"
    for filename in os.listdir(inputDir):
        if fnmatch.fnmatch(filename, '*' + inputExtension):
            filenamels.append(filename[:-len(inputExtension)])
    
    for fn in filenamels:
        inputDataset = 'NETCDF:\"'+ fn + inputExtension +'\":sf'
        outputFile = inputDir + 'Nx.' + fn + '.SUB' + outputExtension
        gdalcmd='gdal_translate -of "ENVI" '+ inputDataset + ' '+ outputFile
        os.system( gdalcmd)
    

    This will use your input directory and form a list of files based on the extension you provide.

    filenamels will contaitn the base names with no extensions and you can then do what you please.