要在Python中从内存中的Google Drive读取文件,您需要使用Google Drive API和google-auth
库
首先,确保您已经安装了所需的库:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
然后,按照以下步骤操作:
from google.colab import auth
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# 如果修改这些范围,请删除token.json。
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
# 认证并获取访问令牌
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
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)
with open('token.json', 'w') as token:
token.write(creds.to_json())
请注意,您需要将credentials.json
替换为您的Google API凭据文件。
from googleapiclient.discovery import build
def get_file_from_drive(file_id):
service = build('drive', 'v3', credentials=creds)
file = service.files().get(fileId=file_id, fields='name, webContentLink').execute()
download_url = file.get('webContentLink')
return download_url
file_id = "your_file_id_here" # 更改为您要读取的文件ID
download_url = get_file_from_drive(file_id)
# 使用requests库下载文件
import requests
response = requests.get(download_url)
if response.status_code == 200:
content = response.content
# 在这里处理文件内容,例如将其保存到内存中或直接处理
else:
print("Error downloading file:", response.status_code)
请确保将your_file_id_here
替换为您要读取的文件的实际ID。
这个示例将从Google Drive下载文件并将其保存在内存中。如果您需要将文件保存到磁盘上,可以将内容写入文件,如下所示:
with open("your_output_file_name.extension", "wb") as f:
f.write(content)
请根据您的需求调整代码。
领取专属 10元无门槛券
手把手带您无忧上云