【问题标题】:download googlesheet and create folder in specific path to save下载 googlesheet 并在特定路径中创建文件夹以保存
【发布时间】:2018-03-31 07:07:33
【问题描述】:

我在下面提到了下载谷歌表格并将其存储在Documents的代码。

library(dplyr)
library(data.table)
library(googlesheets)
library(rJava)

t.start<-Sys.Date()
t.start<-as.character(t.start)

#gs_auth(new_user = TRUE) 
#gs_ls()
#gs_auth()
as<-gs_title("XYZ")
gs_download(as, overwrite = TRUE)

我希望表 XYZ 存储到具有以下提到的条件的特定位置(即 E:\My_data\File)。

  • 我想每天运行此脚本 2 次,我想根据 Sys.Date() 和时间条件重命名文件 XYZ。 (例如,如果 Sys.Date=01/01/2017 且时间 01/01/2017_A_XYZ.xlsx' for >15:00 hrs it should be01/01/2017_B_XYZ.xlsx')
  • 我想根据 Sys.Date()(即年和月)在E:\My_data\File 中自动创建文件夹。如果 Sys.Date()=01/01/2017 则将有一个名为 2017 的文件夹和一个名为 Jan-17 的子文件夹,并且在子文件夹中将有 2 个子文件夹 A (对于文件 B (对于文件 >15:00 hrs for that specific Year/Month)。
  • 如果年/月更改,新文件夹创建的结构相同。

【问题讨论】:

    标签: r matrix dplyr tidyverse


    【解决方案1】:

    您可以使用以下代码来做到这一点:

    # To handle the googlesheets
    require(googlesheets)
    
    # For easier date manipulation
    require(lubridate)
    
    # Get current time
    t <- Sys.time()
    
    # Set your base path and create the basic file structure
    base_path <- "E:/My_data/File"
    dir.create(paste0(base_path, year(t)))
    sub_folder_path <- paste0(base_path, year(t), "/", month(t, label = TRUE), "-", day(t))
    dir.create(sub_folder_path)
    
    AB_split <- ifelse(hour(t)<15, "A", "B")
    dir.create(paste0(sub_folder_path, "/", AB_split))
    
    # Set your gsheet title and the wanted file-name
    ws_title <- "XYZ"
    ws_file_name <- paste0(date(t), "_", AB_split, "_", ws_title, ".xlsx")
    ws_file_path <- paste0(sub_folder_path, "/", AB_split, "/", ws_file_name)
    
    # Download it
    as<-gs_title(ws_title)
    gs_download(as, to = ws_file_path, overwrite = TRUE)
    

    如果出现警告,则尝试创建现有文件夹会导致结果。如果您想抑制警告,请在 suppressWarnings(create.dir(...)) 中包装 create.dir 调用

    我强烈建议 NOT 使用工作表标题,而是使用密钥。见?gs_key

    【讨论】:

    • 谢谢,但我的 gsheet 名称是静态的,我想在运行代码 as&lt;-gs_title 或将其保存到特定位置之前更改它。
    • 对不起……谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-07-06
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    相关资源
    最近更新 更多