我按照this帖子中的说明将 2 个 csv 文件从我的谷歌驱动器下载到我的计算机。这是提供的代码 -
library(googledrive)
library(purrr)
## store the URL you have
folder_url <- "https://drive.google.com/drive/folders/0B7tJg2i5HAo2c0VzVFVhLUdQcnM"
## identify this folder on Drive
## let googledrive know this is a file ID or URL, as opposed to file name
folder <- drive_get(as_id(folder_url))
## identify the csv files in that folder
csv_files <- drive_ls(folder, type = "csv")
## download them
walk(csv_files$id, ~ drive_download(as_id(.x)))
上述说明将 csv 文件下载到我的“文档”文件夹中。我正在尝试使用对最后一段代码的轻微修改来将文件下载到笔记本电脑上的特定文件夹
walk(csv_files$id, ~ drive_download(as_id(.x),
path = "../Desktop/data_folder/,
overwrite = TRUE))
不幸的是,这保存的是单个 .xlsx 文件,该文件不包含任何数据且无法打开。如何更正代码以将这两个文件保存到特定文件夹?
问题在于
path
参数需要完整的文件名,而不仅仅是目录的路径。因此,默认情况下,它使用 goodledrive 方法计算出文件名,并使用它在计算机上的当前工作目录中创建文件。但如果您不想要这种默认行为,您还应该提供文件名。所以基本上有两个选择:
在运行您提供的代码之前,将您的工作目录设置为要将文件下载到的文件夹。 (然后很可能将其改回来是个好主意)
重写脚本,以便使用 googledrive 文件名构建
path
参数。像这样的东西:
path <- "~/Documents/tmp/data_folder/"
for (i in seq_along(csv_files$name)) {
drive_download(
as_id(csv_files$id[[i]]),
path = file.path(path, csv_files$name[[i]]),
overwrite = TRUE
)
}
或者如果您更喜欢使用
walk
:
csv_files %>%
split(csv_files$id) %>%
walk(~drive_download(.$id, path = file.path(path, .$name), overwrite = TRUE))
如果你只有文件而没有子目录,使用
purrr
,你可以这样做:
folder <- drive_get(folder_url)
# find files in folder on GD
files = drive_ls(folder)
files_bind <- bind_rows(files). # make it a tibble
# Batch download the files
map2(files_bind$id, files_bind$name, ~drive_download(as_id(.x), path = file.path(dir_local, .y)))
其中
dir_local
是您机器上的本地目录