I’m working on converting a Google Apps Script to Python and I’m stuck on one specific part. I have JavaScript code that copies files from one folder to another, but I need to find the Python equivalent.
Here’s my current Python attempt:
def duplicate_folder_files(source_folder_id, destination_folder_id):
# Get all files from source directory
file_list = drive.ListFile({'q': f"'{source_folder_id}' in parents"}).GetList()
for item in file_list:
# Need Python equivalent for copying file to target folder
copied_file = item.copy() # This doesn't work as expected
copied_file['parents'] = [{'id': destination_folder_id}]
copied_file.Upload()
source_id = 'your_source_folder_id'
target_id = 'your_target_folder_id'
duplicate_folder_files(source_id, target_id)
The main issue is finding a Python function that works like the JavaScript makeCopy() method. I need to copy files and place them in a specific destination folder. Can anyone help me find the right pydrive method or Google Drive API call to accomplish this file duplication with a target location?
Pydrive doesn’t have a direct copy method on file objects. You’ll need to use the Google Drive API’s files.copy endpoint through pydrive’s auth session. Here’s what worked for me:
def duplicate_folder_files(source_folder_id, destination_folder_id):
file_list = drive.ListFile({'q': f"'{source_folder_id}' in parents"}).GetList()
for item in file_list:
copied_file = drive.CreateFile()
copied_file.auth.service.files().copy(
fileId=item['id'],
body={'parents': [destination_folder_id]}
).execute()
You could also create a new file object with the copied content by setting the original file as a template, but the API copy method works better for larger files. Just make sure your auth scope includes ‘https://www.googleapis.com/auth/drive’ for write permissions.
try using drive.CreateFile() with the file id instead. something like new_file = drive.CreateFile({'id': item['id']}) then copied = new_file.Copy() and set the parent after. worked for me when i had the same issu last month