如何无需手动选择,向Google Colab上传指定本地文件
实现本地指定路径文件自动上传到Google Colab的方法
files.upload()本身不支持传入本地文件路径参数——它依赖浏览器的交互式文件选择弹窗,没法直接指定路径自动上传。但可以通过以下几种方式实现你的需求:
方法1:用Colab本地运行时(直接访问本地文件)
当Colab连接到本地的Jupyter运行时,代码会在你的本地电脑上执行,这时根本不需要“上传”操作,直接用本地文件路径就能读取文件:
- 操作步骤:
- 本地安装Jupyter和对应扩展:
pip install jupyter_http_over_ws jupyter serverextension enable --py jupyter_http_over_ws - 启动本地Jupyter服务器,允许Colab连接:
jupyter notebook --NotebookApp.allow_origin='https://colab.research.google.com' --port=8888 --NotebookApp.port_retries=0 - 在Colab界面右上角点击“连接”→“连接到本地运行时”,输入本地Jupyter给出的URL(比如
http://localhost:8888/?token=xxxx)。 - 连接成功后,直接用本地路径操作文件:
file_path = '/Users/xxx/Documents/test.txt' # 替换成你的本地文件路径 with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 后续可以把内容写入Colab的本地存储,或者直接处理
- 本地安装Jupyter和对应扩展:
方法2:本地脚本自动上传到Colab
如果不想用本地运行时,可以写个本地Python脚本,模拟浏览器的上传请求,自动把指定路径的文件传到Colab:
- 操作步骤:
- 先在Colab里运行一次
files.upload(),打开浏览器开发者工具(F12),切换到“网络”标签,找到上传时的POST请求(一般是包含upload的URL),复制这个请求的URL、Cookie和请求头。 - 本地编写脚本:
import requests # 替换成你从开发者工具复制的信息 upload_url = "https://colab.research.google.com/upload/xxxxxx" cookies = {"COOKIE_NAME": "COOKIE_VALUE"} headers = {"Header-Name": "Header-Value"} file_path = '/Users/xxx/Documents/test.txt' # 你的本地文件路径 with open(file_path, 'rb') as f: # 构造上传的文件参数 files = {'file': (file_path.split('/')[-1], f)} response = requests.post(upload_url, cookies=cookies, headers=headers, files=files) print("上传结果:", response.text) - 运行这个本地脚本,就能自动把指定文件传到Colab当前会话的临时存储里。
- 先在Colab里运行一次
更省心的替代方案
如果经常要传文件,建议把本地文件同步到Google Drive,然后在Colab里挂载Drive直接读取:
from google.colab import drive drive.mount('/content/drive') # 读取Drive里的文件(前提是本地文件已经同步到Drive) file_path = '/content/drive/MyDrive/你的文件路径/test.txt' with open(file_path, 'r', encoding='utf-8') as f: content = f.read()
内容的提问来源于stack exchange,提问作者Swaraag
相关产品推荐
相关产品推荐

