1. 程式人生 > 其它 >【Python基礎】如何向 google colab 上傳檔案?

【Python基礎】如何向 google colab 上傳檔案?

返回:Python基礎 索引頁

分為如下幾個步驟:

Step#1 連線到 google 雲盤:

from google.colab import drive
drive.mount('/content/drive',force_remount = True)


執行成功後,會顯示: Mounted at /content/drive

Step#2 進入子目錄 My Drive:

import os
root_dir = "/content/drive/My Drive/"
os.chdir(root_dir)

確認:

!pwd

顯示: /content/drive/MyDrive

Step#3 建立子目錄 "Colab_Notebooks" :

!mkdir "Colab_Notebooks"


Step#4 進入子目錄:

import os
os.chdir("Colab_Notebooks")


Step#5 再建立下一級及目錄 "Project_folder":

!mkdir "Project_folder"


Step#6 進入剛建好的下一級子目錄:

import os
root_dir = "/content/drive/My Drive/"
project_folder = "Colab_Notebooks/Project_folder/"
os.chdir(root_dir + project_folder)


Step#7 檢視現在所在的目錄:

!pwd

顯示結果:/content/drive/My Drive/Colab_Notebooks/Project_folder

Step#8 現在,開始上傳檔案:

from google.colab import files
files.upload()


執行這一段程式碼後,會顯示一個選擇檔案的對話視窗。
我可以上傳我的檔案: myfunctions.py

此檔案我已經在我的本地C盤準備好了。選擇這個檔案後,就會自動上傳。

在我的 myfunctions.py ,中有如下內容:

def sum_two(num_1, num_2):
  result = num_1 + num_2
  return
result


Step#9 現在,我可以進行跨檔案的函式呼叫:

import myfunctions
result = myfunctions.sum_two(100,200)
print (result)

顯示結果: 300
返回:Python基礎 索引頁