How to copy a google file with Colaboratory?

Viewed 1136

I need to copy a folder and its entire content (with subfolders) to another folder in Google Drive.

I tried using Colaboratory like this:

from google.colab import drive
drive.mount('/content/drive')

%cd /content/drive/MyDrive
%cp -av FOLDER_TO_COPY NEW_FOLDER_COPY

Folders and files are copied except for google files, which gives me the following error:
cp: cannot open 'path_to_file' for reading: Operation not supported
This happends for every .gdoc, .gsheet, .gslides, etc. I cannot convert those files to another format (like .docx or .xlsx) because some have complex formulas that I don't want to screw up.

I also tried this :

from shutil import copyfile

copyfile('path_to_file_to_copy', 
         'destination_path')

But got:
OSError: [Errno 95] Operation not supported: 'path_to_file'

How can I copy Google files using Colaboratory ?

1 Answers

Google Documents are not really regular files, you can not copy them into Google Colab. If you want to import data from them, you can use a library. For example in order to import Google Sheets data, use gspread

!pip install --upgrade gspread

And then

from google.colab import auth
auth.authenticate_user()

import gspread
from oauth2client.client import GoogleCredentials

gc = gspread.authorize(GoogleCredentials.get_application_default())

worksheet = gc.open('Your spreadsheet name').sheet1

# get_all_values gives a list of rows.
rows = worksheet.get_all_values()
print(rows)

# Convert to a DataFrame and render.
import pandas as pd
pd.DataFrame.from_records(rows)

If you want to copy other files, remove the Google Documents from the folder and use the shell command

!cp -r SRC DEST
Related