繁体   English   中英

如何通过 Python 在 Google Drive 中复制文件?

[英]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 中的模板创建一个新文档以及其他与谷歌驱动器,因此它们不能在谷歌应用脚​​本中完成。

网上有一些教程给出了部分答案。 这是您需要做什么的分步指南。

  1. 打开命令提示符并输入(不带引号)“pip install PyDrive”
  2. 按照此处的说明进行第一步 - https://developers.google.com/drive/v3/web/quickstart/python设置帐户
  3. 完成后,单击“下载 JSON”,将下载一个文件。 确保将其重命名为 client_secrets.json,而不是快速入门所说的 client_secret.json。
  4. 接下来,确保将该文件放在与 python 脚本相同的目录中。 如果您从控制台运行脚本,则该目录可能是您的用户名目录。
  5. 我假设您已经知道要放置此文件的文件夹 ID 和要复制的文件 ID。 如果你不知道,这里有关于如何使用 python 找到它的教程,或者你可以在 Docs 中打开它,它会在文件的 URL 中。 基本上输入文件夹的 ID 和文件的 ID,当您运行此脚本时,它将复制所选文件并将其放置在所选文件夹中。
  6. 需要注意的一件事是,在运行时,您的浏览器窗口将打开并请求许可,只需单击接受,然后脚本就会完成。
  7. 为了使其工作,您可能必须启用 API 部分中的 Google Drive API。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM