how to combine many netcdf files into one data file in python

Viewed 241
!pip install wget
import wget
import requests
import numpy as np

days = ['01','15']
months = ['01','02','03','04','05','06','07','08','09','10','11','12']
years = np.array([2010, 2015, 2020])

for year in years:
    for month in months:
        for day in days:
            url = "https://www.ncei.noaa.gov/data/sea-surface-temperature-optimum-interpolation/v2.1/access/avhrr/"+str(year)+str(month)+"/oisst-avhrr-v02r01."+str(year)+str(month)+str(day)+".nc"
            r = requests.get(url, allow_redirects = True)
            open(str(year)+str(month)+str(day)+".nc", "wb").write(r.content)

I have read 72 files (1st day and 15th day each month in 3 years: 2010, 2015, 2020). I want to combine all data into one .nc file in order to read the data I want in python.

1 Answers

After you downloaded all your files, you can open and combine them automatically with xarray.open_mfdataset:

import xarray as xr
import os

DS = xr.open_mfdataset(os.path.join("path/to/files", "*.nc"))
Related