如何用Python无需下载读取Google Drive中的CSV文件?如何获取其URL?
直接读取Google Drive中CSV文件的方案
方式一:转换共享链接为可读取URL
Google Drive不会直接给出可用于程序读取的原始文件URL,但可以通过共享链接转换得到:
- 打开目标CSV文件,点击右上角「共享」,将权限设置为任何知道链接的人可查看
- 复制共享链接(格式类似
https://drive.google.com/file/d/[FILE_ID]/view?usp=sharing),提取其中的[FILE_ID]部分 - 拼接成可直接读取的URL:
https://drive.google.com/uc?id=[FILE_ID]&export=csv
Python读取代码示例
用Pandas直接读取
import pandas as pd # 替换成你的FILE_ID csv_url = "https://drive.google.com/uc?id=12345abcdef&export=csv" df = pd.read_csv(csv_url) # 验证读取结果 print(df.head())
用Requests+CSV模块读取
import requests import csv from io import StringIO csv_url = "https://drive.google.com/uc?id=12345abcdef&export=csv" # 发送请求获取文件内容 response = requests.get(csv_url) # 将响应文本转为可读取的IO对象 csv_data = StringIO(response.text) # 解析CSV内容 reader = csv.reader(csv_data) for row in reader: print(row)
方式二:通过Google Drive API读取(私密文件适用)
如果不想公开文件,可通过API鉴权后读取,无需公开共享:
- 前往Google Cloud Console创建项目,启用「Google Drive API」,生成服务账号密钥(JSON格式)
- 安装依赖包:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib pandas
Python读取代码示例
from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload import pandas as pd from io import BytesIO # 配置参数 SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] # 替换成你的服务账号密钥文件路径 SERVICE_ACCOUNT_FILE = 'service-account-key.json' # 替换成目标文件的FILE_ID FILE_ID = '12345abcdef' # 初始化鉴权凭证 creds = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) # 构建Drive服务客户端 drive_service = build('drive', 'v3', credentials=creds) # 下载文件内容到内存 request = drive_service.files().get_media(fileId=FILE_ID) file_buffer = BytesIO() downloader = MediaIoBaseDownload(file_buffer, request) done = False while not done: status, done = downloader.next_chunk() # 读取内存中的CSV数据 file_buffer.seek(0) df = pd.read_csv(file_buffer) print(df.head())
注意事项
- 方式一操作简单,但要求文件设置为公开可查看,适合无敏感数据的场景
- 方式二安全性更高,支持私密文件,但需要完成API配置步骤,流程稍复杂
内容的提问来源于stack exchange,提问作者Tania
相关产品推荐
相关产品推荐

