如何在R中直接下载并解压GitHub上的压缩文件?
问题描述
尝试在R中直接从GitHub下载并解压文件夹,手动下载链接的文件可正常解压,但通过R操作时遇到以下问题:
- 直接执行
utils::unzip("https://github.com/dylangomes/SO/blob/main/Shape.zip"),出现警告error 1 in extracting from zip file,无文件下载解压 - 用
utils::download.file("https://github.com/dylangomes/SO/blob/main/Shape.zip")下载后,文件无法手动解压(提示为空),执行utils::unzip("Shape.zip")仍报相同错误 - 添加
?raw=TRUE后执行utils::download.file("https://github.com/dylangomes/SO/blob/main/Shape.zip?raw=TRUE","Shape.zip"),解压时出现警告internal error in 'unz' code,仍未成功
解决方案
问题出在download.file()的默认下载模式会将二进制的zip文件当作文本文件处理,导致文件损坏。只需添加mode="wb"参数以二进制模式下载即可:
# 二进制模式下载raw格式的zip文件 utils::download.file("https://github.com/dylangomes/SO/blob/main/Shape.zip?raw=TRUE", destfile = "Shape.zip", mode = "wb") # 解压文件到工作目录 utils::unzip("Shape.zip")
mode="wb"确保下载过程中保留zip文件的二进制结构,避免编码转换破坏文件完整性,这样后续的解压操作就能正常执行。
内容的提问来源于stack exchange,提问作者Dylan_Gomes
相关产品推荐
相关产品推荐

