Search code examples
rgoogle-drive-api

How do I programmatically locate my Google Drive folder using R?


This is the same question as here, except I needed to do that in R.

Locating the google drive folder on the computer is useful when you need to access a file within the google drive folder, but this google driver folder has different paths on your different computers, which makes the sharing of script difficult.

I have not found solutions on how to do that in R, so I thought it might be useful, for anyone else having the same question, to open a thread here. I have prepared a solution for R based on the link above.

I would be glad to read a better/simpler solution than the one I will present here.

In addition, my solution will likely only work for Windows users, so a solution for other OS or a more general cross-OS solution would be welcome.


Solution

  • The idea is to access the google drive file database with the RSQLite library, and execute a query which will return the root path of the google drive folder. The following code executes this:

    # Get the path to the google drive database
    googledrivedb <- paste0(Sys.getenv("LOCALAPPDATA"), "/Google\\Drive\\user_default\\sync_config.db")
    # Correct backslashes to slashes so that R can interact with the folders
    googledrivedb <- gsub("\\\\", "/", googledrivedb)
    
    # Load SQL interface libraries
    library(DBI)
    library(RSQLite)
    
    # Connect to the google drive file database
    con <-dbConnect(RSQLite::SQLite(), dbname = googledrivedb)
    
    # Make a query which will return the path to the root folder of google drive
    path <- dbGetQuery(con, "select * from data where entry_key='local_sync_root_path'")$data_value
    
    # Remove unnecessary characters in the path (I had "\\\?\" in my path - I don't know how it will look like on other computers)
    path <- substring(path,
                      5)
    # Correct backslashes to slashes so that R can interact with the folders
    path <- gsub("\\\\", "/", path)
    # Close the connection to the database
    dbDisconnect(con)
    
    # Show the obtained path
    path
    

    In my case the result was: "C:/Google Drive"