Convert a .sav file to .csv file in Python

前端 未结 4 564
面向向阳花
面向向阳花 2021-01-17 07:28

I want to convert the contents of *.sav file into a *.csv file in Python. I have written the following lines of code to access the details of variables in *.sav file. Now, I

相关标签:
4条回答
  • 2021-01-17 07:37

    I could solve my problem by changing the requisite output format and here is my code:

    import scipy.io as spio
    import numpy as np
    import csv
    
    on2file = 'ON2_2016_112m_220415.sav'   # i/p file
    outfile = 'ON2_2016_112m_220415.csv'   # o/p file
    
    # Read i/p file
    s = spio.readsav(on2file, python_dict=True, verbose=True)
    
    # Creating Grid
    #d_lat = s["d_lat"]
    #d_lon = s["d_lon"]
    lat = np.arange(-90,90,1.78218)  # (101,)
    lon = np.arange(-180,180,1.78218)     # (202,)
    ylat,xlon = np.meshgrid(lat,lon)
    
    on2grid = np.asarray(s["on2_grid"])
    on2gridsmooth = np.asarray(s["on2_grid_smooth"])
    
    nrows = len(on2grid)
    ncols = len(on2grid[0])
    
    xlon_grid = xlon.reshape(nrows*ncols,1)
    ylat_grid = ylat.reshape(nrows*ncols,1)
    on2grid_new = on2grid.reshape(nrows*ncols,1)
    on2gridsmooth_new = on2gridsmooth.reshape(nrows*ncols,1)
    
    # Concatenation
    allgriddata = np.concatenate((xlon_grid, ylat_grid, on2grid_new, on2gridsmooth_new),axis=1)
    
    # Writing o/p file
    f_handle = file(outfile,'a')
    np.savetxt(f_handle,allgriddata,delimiter=",",fmt='%0.3f',header="longitude, latitude, on2_grid, on2_grid_smooth")
    f_handle.close()
    
    0 讨论(0)
  • 2021-01-17 07:42

    I know that this solution uses R instead of python, but it is really simple and works well.

    library(foreign)
    write.table(read.spss("inFile.sav"), file="outFile.csv", quote = TRUE, sep = ",")
    
    0 讨论(0)
  • 2021-01-17 07:47

    The column of latitude and longitude in the extracted files using your code looks interchanged. Further the latitude scale ranges from 0 to 180 (not +90 0 -90)) ...whether the 0 starts from the top. Pl. comment.

    0 讨论(0)
  • 2021-01-17 07:50

    I am working on it and, for the moment, this is my 'poor' solution:

    First I import module savReaderWriter to convert .sav file into structured array Second I import module numpy to convert structured array into csv:

    import savReaderWriter 
    import numpy as np
    
    reader_np = savReaderWriter.SavReaderNp("infile.sav")
    array = reader_np.to_structured_array("outfile.dat") 
    np.savetxt("outfile2.csv", array, delimiter=",")
    reader_np.close()
    

    The problem is that I lose name atributes during conversion. I will try to solve the problem.

    0 讨论(0)
提交回复
热议问题