【问题标题】:download.file from url without specifying filename using R从url下载.file而不使用R指定文件名
【发布时间】:2021-12-21 06:42:02
【问题描述】:

我正在尝试从 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 = '.')

文件损坏导致解压失败

【问题讨论】:

  • 你可以使用temp &lt;- tempfile(); download.file(url, temp)
  • 它用这个下载,但我找不到在哪里,它不是工作目录。有没有办法指定目录而不指定文件名?

标签: r downloadfile


【解决方案1】:

destfile ='Denmark_shapefile.zip' 仅指定下载文件应具有的名称。你可以在里面写任何你想写的东西。

您的代码完全适合我,但您可以尝试使用这个下载语句而不是您的,它指定用于编写并且是二进制安全的。

download.file(url, destfile ='Denmark_shapefile.zip', mode='wb', cacheOK=FALSE)

【讨论】:

  • 为什么我需要指定任何东西?服务器上的文件有名字,不能直接下载吗?我认为文件的这种重命名是导致解压缩失败的原因。
  • 我刚刚尝试按原样执行您的代码 1:1,它对我来说完全没问题。它解压到与Denmark_shapefile.zip相同的目录中
  • 我收到错误“警告消息:在 unzip(zipfile = "Denmark_shapefile.zip", exdir = ".") 中:'unz' 代码中的内部错误'
  • 你能告诉我你得到的确切错误吗?
  • 我的意思是我没有编辑就复制了你的代码。您可以尝试使用此下载语句吗? download.file(url, destfile ='Denmark_shapefile.zip', mode='wb', cacheOK=FALSE)
【解决方案2】:

一种方法是,

    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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多