Python转化hdf为csv代码
最近因为项目的原因,试着分析卫星数据。在各个平台上学习了很多知识,发现一个很好用的python代码。前来分享。
hdf(Hierarchical Data Format)包括(HDF4, HDF5)文件是一种分层结构的文件格式,用来储存较大量的文件数据。从NASA下载到的卫星数据,好多都是这一种格式的。hdf可以用Java-Based 的HDF Viewer打开。如下图:
但是,只能看到一些层级别的信息。如果需要进一步获取或处理数据,其中的一个方法便是转化为csv 文件。我在网上找到一段NASA官方提供的代码,标题为:Read, Map and Extract MODIS Aerosol Data Using Python Scripts. 来自于Applied Remote Sensing Training Program. 作者为:Pawan Gupta & Melanie Follette-Cook. 时间为:2018年1月17-22号。
运行python之前,需要pyhdf包,我本人费了好长时间才安装好。参考解决办法为:https://blog.csdn.net/vonuo/article/details/74853213 在此,感谢提供这个办法的作者。
代码如下:
#!/usr/bin/python
'''
Module: read_mod_aerosol_and_dump_ascii.py
==========================================================================================
Disclaimer: The code is for demonstration purposes only. Users are responsible to check for accuracy and revise to fit their objective.
Author: Justin Roberts-Pierel, 2015
Organization: NASA ARSET
Purpose: To save a MODIS HDF4 file (or series of files) in ASCII format, saving time, lat, lon, and other SDS dependent on file type
See the README associated with this module for more information.
Este script toma la lista de archivos de fileList.txt generado con createflist.sh y automaticamente
convierte los hdf en txt
Es distinto al que se encuentra en la pagina de la NASA porque no pregunta nada, solo hace la conversion
sobre los hdf que esten en fileList.txt
==========================================================================================
'''
#import necessary modules
from pyhdf import SD
import numpy as np
import time
import calendar
import sys
#This uses the file "fileList.txt", containing the list of files, in order to read the files
try:
fileList=open('filelist.txt','r')
except:
print('Did not find a text file containing file names (perhaps name does not match)')
sys.exit()
#loops through all files listed in the text file
for FILE_NAME in fileList:
FILE_NAME=FILE_NAME.strip()
user_input=input('\nWould you like to process\n' + FILE_NAME + '\n\n(Y/N)')
if(user_input == 'N' or user_input == 'n'):
break
else:
if '3K' in FILE_NAME: #then this is a 3km MODIS file
print('This is a 3km MODIS file. Saving... ')
#saves all the SDS to be outputted to ASCII in a dictionary
dataFields=dict([