<h2>答复</h2>
<p>我建议您按照这个<a href="https://developers.google.com/drive/api/v3/quickstart/python" rel="nofollow noreferrer">guide</a>开始使用驱动器API和Python。成功运行示例后,请将<code># Call the Drive v3 API</code>上方的行替换为驱动器中的<a href="https://developers.google.com/drive/api/v3/folder#create_a_folder" rel="nofollow noreferrer">code</a>文件夹。此外,为了创建文件夹,您必须修改作用域,在这种情况下,您可以使用<code>https://www.googleapis.com/auth/drive.file</code>。最终结果如下所示:</p>
<h2>代码</h2>
<pre><code>from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.file']
def main():
"""Shows basic usage of the Drive v3 API.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
folder_name = 'folder A'
file_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder'
}
file = drive_service.files().create(body=file_metadata,
fields='id').execute()
print('Folder ID: %s' % file.get('id'))
if __name__ == '__main__':
main()
</code></pre>
<h2>参考资料:</h2>
<ul>
<li><a href="https://developers.google.com/drive/api/v3/quickstart/python" rel="nofollow noreferrer">Drive API: Python Quickstart</a></li>
<li><a href="https://developers.google.com/drive/api/v3/folder#create_a_folder" rel="nofollow noreferrer">Drive API: Create a folder</a></li>
</ul>