Skip to content

Commit

Permalink
Use context manager to open and close nc file
Browse files Browse the repository at this point in the history
  • Loading branch information
chrowe authored Oct 31, 2024
1 parent fcb6570 commit 9df8d4b
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions city_metrix/layers/era_5_hottest_day.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,13 @@ def hourly_mean_temperature(image):
},
f'download_{i}.nc')

dataarray = xr.open_dataset(f'download_{i}.nc')
with xr.open_dataset(f'download_{i}.nc') as dataarray:
# Subset times for the day
times = [valid_time.astype('datetime64[s]').astype(datetime).replace(tzinfo=pytz.UTC) for valid_time in dataarray['valid_time'].values]
indices = [i for i, value in enumerate(times) if value in utc_times]
subset_dataarray = dataarray.isel(valid_time=indices)

# Subset times for the day
times = [valid_time.astype('datetime64[s]').astype(datetime).replace(tzinfo=pytz.UTC) for valid_time in dataarray['valid_time'].values]
indices = [i for i, value in enumerate(times) if value in utc_times]
subset_dataarray = dataarray.isel(valid_time=indices)

dataarray_list.append(subset_dataarray)
dataarray_list.append(subset_dataarray)

# Remove local file
os.remove(f'download_{i}.nc')
Expand Down

0 comments on commit 9df8d4b

Please sign in to comment.