You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言无法下载指定URL的.zip文件并提取.shp文件的问题

问题:R语言下载并读取Zip中的Shapefile失败

需求说明

需要自动化下载NOAA的多个日期的Zip格式Shapefile包,提取其中指定的.shp文件(示例目标:94e2701.shp,对应Zip包:shp_94e_2018122701.zip)。

错误现象与原代码

原测试代码:

shp_url = "https://www.wpc.ncep.noaa.gov/archives/ero/20181227/shp_94e_2018122701.zip"
tmp = tempfile()

download.file(shp_url,tmp,mode="wb")
# 尝试过不使用"mode"参数,结果相同

f_name = "94e2701.shp"
data <- sf::st_read(unz(tmp,f_name))
# 错误提示:Cannot open "3"; The file doesn't seem to exist.
unlink(tmp)

问题点:

  • 下载后的临时文件无.zip后缀,系统无法识别为压缩包;
  • 直接读取单个.shp文件会失败——Shapefile依赖配套的.dbf、.shx等文件,仅读取单个文件无法正常解析。

修正方案

  1. 给临时文件添加.zip后缀,确保压缩包格式被正确识别
  2. 创建临时目录用于解压Zip包,避免依赖文件缺失
  3. 读取解压后的完整Shapefile文件组
  4. 清理临时文件与目录

修正后的代码:

library(sf)

shp_url <- "https://www.wpc.ncep.noaa.gov/archives/ero/20181227/shp_94e_2018122701.zip"
# 创建带.zip后缀的临时文件
tmp_zip <- tempfile(fileext = ".zip")
# 创建临时目录用于解压
tmp_dir <- tempdir()

# 下载压缩包
download.file(shp_url, tmp_zip, mode = "wb")

# 解压整个Zip包到临时目录
unzip(tmp_zip, exdir = tmp_dir)

# 读取目标shp文件(sf会自动查找配套的.dbf/.shx等文件)
target_shp <- "94e2701.shp"
data <- st_read(file.path(tmp_dir, target_shp))

# 清理临时文件与目录
unlink(tmp_zip)
unlink(tmp_dir, recursive = TRUE)

# 查看数据结构
head(data)

批量处理扩展思路

若要处理多个日期,可构建日期序列,动态生成对应Zip的URL(需确认NOAA的文件命名规则统一):

# 示例:生成2018年12月27日-29日的目标URL
dates <- as.Date(c("2018-12-27", "2018-12-28", "2018-12-29"))
for (date in dates) {
  date_str <- format(date, "%Y%m%d")
  # 按规则构造URL
  shp_url <- sprintf("https://www.wpc.ncep.noaa.gov/archives/ero/%s/shp_94e_%s01.zip", date_str, date_str)
  # 重复上述下载-解压-读取流程...
}

内容的提问来源于stack exchange,提问作者James S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:25:20