![](/img/trans.png)
[英]How can I copy a file stored in S3 - like an Excel file - into Google Drive via a Lambda function?
[英]How can I make a copy of a file in Google Drive via Python?
我在 Google Apps 脚本中编写了一个简短的函数,可以复制存储在 Google Drive 上的特定文件。 它的目的是这个文件是一个模板,每次我想为工作创建一个新文档时,我都会复制这个模板并更改文档的标题。 我编写的用于复制文件并将其存储在我想要的特定文件夹中的代码非常简单:
function copyFile() {
var file = DriveApp.getFileById("############################################");
var folder = DriveApp.getFolderById("############################");
var filename = "Copy of Template";
file.makeCopy(filename, folder);
}
此函数获取基于 ID 的特定文件和基于 ID 的特定文件夹,并将副本授权“模板副本”放入该文件夹。
我一直在寻找,我似乎找不到这个。 有没有办法做同样的事情,但使用 Python 代替? 或者,至少有没有办法让 Python 以某种方式调用该函数来运行该函数? 我需要在 Python 中完成此操作,因为我正在编写一个脚本,每当我开始一个新的工作项目时,它会同时执行许多功能,例如从 Google Drive 中的模板创建一个新文档以及其他与谷歌驱动器,因此它们不能在谷歌应用脚本中完成。
网上有一些教程给出了部分答案。 这是您需要做什么的分步指南。
Python脚本:
## Create a new Document in Google Drive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
folder = "########"
title = "Copy of my other file"
file = "############"
drive.auth.service.files().copy(fileId=file,
body={"parents": [{"kind": "drive#fileLink",
"id": folder}], 'title': title}).execute()
来自https://developers.google.com/drive/v2/reference/files/copy
from apiclient import errors
# ...
def copy_file(service, origin_file_id, copy_title):
"""Copy an existing file.
Args:
service: Drive API service instance.
origin_file_id: ID of the origin file to copy.
copy_title: Title of the copy.
Returns:
The copied file if successful, None otherwise.
"""
copied_file = {'title': copy_title}
try:
return service.files().copy(
fileId=origin_file_id, body=copied_file).execute()
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None
使用 API v3:
将文件复制到具有不同名称的目录。
service.files().copy(fileId='PutFileIDHere', body={"parents": ['ParentFolderID'], 'name': 'NewFileName'} ).execute()
对我来说,@Rashi 的答案做了一个小的修改。
代替:
'name': 'NewFileName'
这有效:
'title': 'NewFileName'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.