首页 > 解决方案 > 从url下载.file而不使用R指定文件名

问题描述

我正在尝试从 url 下载文件。如果我手动下载并解压缩它可以正常工作,但是,使用 download.file zip 已损坏。我想知道这是否与手动指定文件名有关。为什么在使用 download.file 函数时需要这样做?难道不能简单地指定一个 url 和文件夹,然后下载服务器上命名的文件吗?

##using R
##download url
url <- 'https://www.eea.europa.eu/data-and-maps/data/eea-reference-grids-2/gis-files/denmark-shapefile/at_download/file'

download.file(url, destfile ='Denmark_shapefile.zip')

unzip(zipfile = 'Denmark_shapefile.zip', exdir = '.')

由于文件损坏,解压失败

标签: r

解决方案


一种方法是,

    url <- 'https://www.eea.europa.eu/data-and-maps/data/eea-reference-grids-2/gis-
files/denmark-shapefile/at_download/file'

您的工作目录是文件已下载

library(stringr)
fold = str_replace_all(getwd(), '/', '\\\\')

随机文件名被分配给 zip 文件。

fil = tempfile(pattern = "file", tmpdir = fold, fileext = '.zip')
download.file(url, fil, mode = 'wb')

推荐阅读