使用R批量下载URL中NetCDF文件失败,文件损坏求助
Hey Michel, sorry to hear your batch NetCDF downloads are ending up corrupted—let's break down the likely issues and fix this step by step!
1. The Biggest Culprit: Invalid Dates
Your current day vector includes 31 days for every month, but not all months have 31 days (e.g., February 2017 only has 28 days). When your loop hits a date like 20170230, the server returns a 404 error page instead of a valid NetCDF file. That "file" you're downloading is actually HTML error text, which is why it's corrupted when you try to open it.
Fix: Generate Valid Dates Automatically
Use R's date handling functions to create only real, existing dates for your target years/months. This avoids hitting invalid URLs entirely:
library(lubridate) # Define your target date range start_date <- ymd("2016-01-01") end_date <- ymd("2017-02-28") # Generate a sequence of all valid dates in the range all_dates <- seq.Date(start_date, end_date, by = "day") # Loop through each valid date for (date in all_dates) { y <- year(date) m <- sprintf("%02d", month(date)) d <- sprintf("%02d", day(date)) # Build URL and destination file path url <- paste0("http://thredds.met.no/thredds/fileServer/metusers/senorge2/seNorge2/provisional_archive/PREC1d/gridded_dataset/", y, m, "/seNorge_v2_0_PREC1d_grid_", y, m, d, "_", y, m, d, ".nc") dest_file <- paste0("seNorge_v2_0_PREC1d_grid_", y, m, d, "_", y, m, d, ".nc") # Download with error handling tryCatch({ download.file(url, destfile = dest_file, method = "curl", mode = "wb") # Verify file is valid (check size first) if (file.size(dest_file) < 1000) { # Adjust threshold based on expected file size warning(paste("File", dest_file, "is suspiciously small—likely a 404 error page")) file.remove(dest_file) } else { # Optional: Verify with ncdf4 package library(ncdf4) nc <- nc_open(dest_file) nc_close(nc) message(paste("Successfully downloaded and verified", dest_file)) } }, error = function(e) { message(paste("Failed to download", url, ":", e$message)) }) # Add a small delay to avoid overwhelming the server Sys.sleep(0.5) }
2. Double-Check Download Settings
- For
download.file, you already havemode="wb"(binary mode) which is critical for NetCDF files—don't remove that! - If you prefer using
wget, make sure you explicitly specify the output file with-Oto avoid naming issues, and add flags to handle potential server quirks:
Thesystem(paste("wget --no-check-certificate -O", dest_file, url), wait = TRUE)--no-check-certificateflag helps if there are SSL certificate issues with the server.
3. Add Validation & Error Handling
Even with valid dates, network blips can cause corrupted downloads. Adding checks like:
- Checking file size against a minimum threshold (valid NetCDF files for this dataset are likely several MBs, not KB)
- Using
ncdf4::nc_opento attempt opening the file (if it fails, the file is corrupted) - Catching errors during download to avoid crashing the entire loop
4. Optional: Parallelize Downloads
If you need to speed things up, use the foreach or furrr packages to download files in parallel (just be mindful not to flood the server with too many concurrent requests):
library(foreach) library(doParallel) cl <- makeCluster(4) # Use 4 cores registerDoParallel(cl) foreach(date = all_dates, .packages = c("lubridate", "ncdf4")) %dopar% { # Same download/validation code as above } stopCluster(cl)
内容的提问来源于stack exchange,提问作者Michel Mesquita

