1 批量移动文件
import os
to_path = 'H:/China/LAI'
for year in range ( 2003 , 2021 ) :
os. chdir( r'H:/China/LAI/%d' % year)
os. system( 'move *.tif %s' % to_path)
2 批量删除文件
import os
for i in range ( 2003 , 2021 ) :
for j in range ( 1 , 13 ) :
os. system( 'cd H:/MYD15A2H/%d/%d/ && del *.hdf && del *.prm' % ( i, j) )
3 批量修改文件
def rename ( startyear= 2001 , endyear= 2003 , inputpath= '' ) :
"""save入参数介绍
循环将各年份中的文件名修改
比如:tmp2001_1======>tmp200101
:startyear:开始年份
:endyear:结束年份+1
:inputpath:输入数据目录,比如'H:/test/'
"""
import os
for year in range ( startyear, endyear) :
path = inputpath+ '/' + str ( year)
os. chdir( path)
fileList= os. listdir( path)
n = 0
for i in fileList:
oldname= path+ '/' + fileList[ n]
print ( oldname)
if fileList[ n] [ - 5 ] == '_' :
newname = path+ '/' + fileList[ n] [ : - 5 ] + '0' + fileList[ n] [ - 4 ] + '.nc'
else :
newname = path+ '/' + fileList[ n] [ : - 6 ] + fileList[ n] [ - 5 : - 3 ] + '.nc'
print ( newname)
print ( oldname, '==============>' , newname)
n = n+ 1
startyear= 2003
endyear= 2021
inputpath= 'H:/China/EVI/nc/'
rename( startyear= startyear, endyear= endyear, inputpath= inputpath)
4 批量给数据添加时间维度
import xarray as xr
import pandas as pd
import glob
alltimes = [ ]
years = np. arange( 2001 , 2021 , 1 )
months = np. arange( 1 , 12 + 1 , 1 )
for year in years:
for month in months:
newtime = str ( year) + '-' + str ( month) + '-' + '15'
alltimes. append( newtime)
def dims_time ( data, nu) :
datetime_series= pd. Series( pd. date_range( alltimes[ nu] , periods= 1 , freq= 'd' ) )
datetime_series= datetime_series. values. astype( "datetime64[D]" )
times= xr. DataArray( datetime_series, [ ( 'time' , datetime_series) ] )
timedata= data. expand_dims( time= times)
return timedata
rasters2 = glob. glob( r'H:\Climate\pre\*.nc' )
for i, raster in enumerate ( rasters2) :
da= xr. open_dataset( raster)
var= da. pre* 0.1
newdata= dims_time( var, i)
print ( raster. split( '\\' ) [ 3 ] , '========>' , newdata. time. values)
print ( np. nanmean( newdata. values) )
newdata. to_netcdf( 'H:/Climate/test/' + raster. split( '\\' ) [ 3 ] )