Printing one variable from a netCDF file using Python
Question: I am trying to take one variable from a netCDF file and print it. here is my
code

    
    
    import netCDF4
    import netCDF4_utils
    from netCDF4 import Dataset
    from numpy.random import uniform
    import csv
    
    B = []
    rootgrp = Dataset('test.cdf', 'r', format = 'NETCDF4')
    f = open('testoutput.csv','wb')
    
    b = (rootgrp.variables['grid_optical_depth'][:])
    for x in b:
            B.append(x)
    f.write(str(B))
    rootgrp.close()
    f.close()
    

when I run this I get a very large set of data that seems to be repeating, but
I don't see how my for loop is doing that, shouldn't it only run through the
data set once? also could anyone speak to why the data prints out in sets of
four per line? If I run `print rootgrp.variables['grid_optical_depth']` I get

    
    
    <type 'netCDF4.Variable'>
    float32 grid_optical_depth(grid_time, range)
        long_name: Grid_Aerosol_Optical_Depth_Profile
        units: (n/a)
        temporal_average: 20.0
    unlimited dimensions:
    current shape = (1440, 399)
    

so does that mean that two of the numbers correspond to the grid_time and rage
value? I don't think this is the case because all the numbers are much smaller
then 1 (on the order of 10^-3 and -4).

Any help is appreciated


Answer: I tested your code with another file and it gives the intended results:
printing a variable from a netCDF file to a csv file. It does not print the
variable twice, perhaps this is a characteristic of your file.

Your `grid_optical_depth` variable has a shape of `(1440, 399)`, the first
index corresponding to the dimension `grid_time` and the second to the
dimension `range`. When you do the loop `for x in b:`, you are appending each
column of the variable (up to 1440), and each column will have 399 rows.

Besides, you don't actually need the loop. If you set numpy's print options to
show the full array, you can just print the whole array directly to a string,
like this:

    
    
    import numpy as np
    import netCDF4
    rootgrp = netCDF4.Dataset('test.cdf', 'r', format='NETCDF4')
    f = open('testoutput.csv','wb')
    
    np.set_printoptions(threshold='nan')
    f.write(str(rootgrp.variables['grid_optical_depth'][:]))
    f.close()
    rootgrp.close()
    

If all you want is to write a netCDF variable into text format, then I
strongly consider you get acquainted with the
[ncdump](http://www.unidata.ucar.edu/software/netcdf/docs/netcdf/ncdump.html)
program.

