如何提取更多文件(如100个文件)?

时间:2017-01-02 21:33:37

标签: python

如何提取更多文件(如100个文件)

pw_201701010000.nc 
pw_201701010100.nc 
pw_201701010200.nc 
pw_201701010300.nc 
... 
pw_201701022300.nc

代码:

from numpy import *
from netCDF4 import Dataset

fname = 'pw_201701010000'

f = Dataset(fname+'.nc')
print (f.variables)
data = f.variables['pw'][0][:]
data = data-0.
time = f.variables['time'][:]
lat = f.variables['latitude'][:]
lon = f.variables['longitude'][:]
f.close()


f = open(fname+'.txt','w')
for i in range(len(lat)):
    for j in range(len(lon)):
        if lat[i]>=-3.0 and lat[i]<=0 and lon[j]>=116.0 and lon[j]<=119.0:
            #f.write(('%f\t%f\t%f\n')%(lat[i],lon[j],data[i,j]))
            f.write(('%f\t')%(data[i,j]))
    if lat[i]>=-3.0 and lat[i]<=0:
        f.write('\n')
f.close()

1 个答案:

答案 0 :(得分:1)

如果您使用glob获取所有.nc个文件,这很简单:

import glob
from numpy import *
from netCDF4 import Dataset

for fname in glob.iglob("*.nc"):

    f = Dataset(fname)
    print(f.variables)
    data = f.variables['pw'][0][:]
    data = data-0.
    time = f.variables['time'][:]
    lat = f.variables['latitude'][:]
    lon = f.variables['longitude'][:]
    f.close()

    with open(fname.rsplit('.',1)[0]+'.txt','w') as f:
        for i in range(len(lat)):
            for j in range(len(lon)):
                if lat[i]>=-3.0 and lat[i]<=0 and lon[j]>=116.0 and lon[j]<=119.0:
                    #f.write(('%f\t%f\t%f\n')%(lat[i],lon[j],data[i,j]))
                    f.write(('%f\t')%(data[i,j]))
            if lat[i]>=-3.0 and lat[i]<=0:
                f.write('\n')