Reputation: 3709
Is it possible to perform a "deep" copy of Google Drive files, so that the copied file doesn't point to the same file object as the original? I'd like to be able to copy a file and have the copy be completely independent of the original, such that any modifications that are made to the copy don't also show up in the original. Using the following code I'm able to:
But the problem is that any changes that are made to the copy also show up in the original. I'd like for the copied file to be a completely independent file. Is this possible?
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
#load previously generated credentials file
gauth.LoadCredentialsFile("mycreds3.txt")
drive = GoogleDrive(gauth)
#define ID of file to be copied
template_file_id = "1RQWYeeth-Ph ..."
#create a new folder to store the copied file
folder = drive.CreateFile({"title":"test_folder", 'mimeType': 'application/vnd.google-apps.folder'})
folder.Upload()
folder_id = folder['id']
#copy file into newly created folder
drive.auth.service.files().copy(fileId=template_file_id,body={'parents':[{"kind":'drive#file',"id":folder_id}], 'title':'new_file_title'}).execute()
EDIT:
I was able to perform a deep copy by copying a shared file. When a file is copied from a shared file (which doesn't have a shortcut in Drive that links to the original), a deep copy is created such that modifications to the copied file don't show up in the original. Copying shared folders this way threw an error, but individual files worked just fine.
destination_folder_id = 'YTRCA18EE ...'
shared_files = drive.ListFile({'q':'sharedWithMe'}).GetList()
for file in shared_files:
drive.auth.service.files().copy(fileId=file['id'],body={'parents':[{"kind":'drive#file',"id":destination_folder_id}], 'title':file['title']}).execute()
Upvotes: 1
Views: 681
Reputation: 117146
Lets take this step by step
The way this library works is that all calls must go through a service. In this case a drive service will give your application access to all the methods available in the Google drive api.
drive_service = GoogleDrive(gauth)
You have named your variable drive when creating your drive_service for constastancy.
Creating a new file and uploading it to google drive is a two part process. The first part is the file_metadata , that being the name and description of the file. The second is the media or the actual file data itself.
file_metadata = {'name': 'photo.jpg'}
media = MediaFileUpload('files/photo.jpg', mimetype='image/jpeg')
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print 'File ID: %s' % file.get('id')
Note: all fields does is limit the response returned by the api to only the file id.
Upvotes: 1