在 Google Colab 中导入 .py 文件 [英] Importing .py files in Google Colab
问题描述
有什么方法可以将我的代码上传到 .py 文件中并将它们导入到 colab 代码单元中?
Is there any way to upload my code in .py files and import them in colab code cells?
我发现的另一种方法是创建一个本地 Jupyter notebook 然后将其上传到 Colab,这是唯一的方法吗?
The other way I found is to create a local Jupyter notebook then upload it to Colab, is it the only way?
推荐答案
可以先保存,再导入.
from google.colab import files
src = list(files.upload().values())[0]
open('mylib.py','wb').write(src)
import mylib
更新(2018 年 11 月):现在您可以通过
Update (nov 2018): Now you can upload easily by
- 单击 [>] 打开左窗格
- 选择文件标签
- 点击[上传]并选择你的[mylib.py]
- 导入 mylib
更新(2019 年 10 月):如果不想每次都上传,可以将其存储在 S3 中并挂载到 Colab,如这个要点
Update (oct 2019): If you don't want to upload every time, you can store it in S3 and mount it to Colab, as shown in this gist
更新(2020 年 4 月):现在您可以自动挂载 Google 云端硬盘了.从云端硬盘复制它比上传更容易.
Update (apr 2020): Now that you can mount your Google Drive automatically. It is easier to just copy it from Drive than upload it.
- 将
mylib.py
存储在您的云端硬盘中 - 打开一个新的 Colab
- 打开(左侧)侧面板,选择
Files
视图 - 点击
Mount Drive
,然后Connect to Google Drive
- 通过
!cp drive/MyDrive/mylib.py 复制它.
导入 mylib
- Store
mylib.py
in your Drive - Open a new Colab
- Open the (left)side pane, select
Files
view - Click
Mount Drive
thenConnect to Google Drive
- Copy it by
!cp drive/MyDrive/mylib.py .
import mylib
这篇关于在 Google Colab 中导入 .py 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!