[GIS] GDAL translate -AttributeError: ‘NoneType’ object has no attribute ‘RasterCount’

gdalgeotiff-tiffnetcdfpython

I am trying to convert a netCDF file to geotiff, I am getting he following error at line 14. I just can't seem to figure out what the problem is, I will put the whole code below. Please help,

AttributeError                            Traceback (most recent call last)
<ipython-input-14-d0e422b9cf8e> in <module>()
     12     driver = gdal.GetDriverByName(fileFormat)
     13     band = 1
---> 14     numBands = dataset.RasterCount
     15 
     16     # Write gdal_translate into multiple bands - again specific to my .nc file

AttributeError: 'NoneType' object has no attribute 'RasterCount'

The code :

Step 1: GDAL Translate to convert to TIFF


import gdal
import datetime

for i in range(1980,2010):
    #change this to suit your .nc filename pattern
    fileName = 'full_data_v6_precip_05' +str(i)+ '.nc'
    year = i
    startDate = datetime.date(year, 1, 1)
    # create new file to write command prompt lines to
    file = open('commandpromptoutput.txt','a')

    #parse .nc file to count how many bands
    fileFormat = "NETCDF"
    dataset = gdal.Open(fileName,gdal.GA_ReadOnly)
    driver = gdal.GetDriverByName(fileFormat)
    band = 1
    numBands = dataset.RasterCount



# Write gdal_translate into multiple bands - again specific to my .nc file
    for i in range(numBands):
        file.write("gdal_translate -a_srs EPSG:4326 -b "+str(band)+" "+ fileName +" "+ str(startDate) + ".tif\n")
        startDate = startDate + datetime.timedelta(days=1)
        band += 1


    file.close()

Step 3: Upload to EE from GCloud

from datetime import datetime
import os
path = "C:\WorkingDirectory"
# create new file to write command prompt lines to
file = open('commandpromptoutput.txt','a')
epoch = datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0

for root, dir, files in os.walk(path):
    for filename in files:
        filedate = datetime.strptime(filename[0:-4], '%Y-%m-%d')
        filetime = unix_time_millis(filedate)
        file.write('earthengine upload image --asset_id users/xxx'+str(filename[0:-4])+' --nodata_value -999 --property system:time_start='+ str(int(filetime))+ ' gs://xxx' + str(filename)+"\n")

file.close()

Best Answer

First, test that the gdal.Open(...) worked:

dataset = gdal.Open(filename, gdal.GA_ReadOnly)
if dataset is None:
    ...
else:
    ...