
簡介
Google Colab 提供了一個方便的雲端 Python 開發環境。與 Google 雲端硬碟 (Google Drive) 整合是 Colab 的一項重要功能,它讓您可以:
- 直接在 Colab 中存取您雲端硬碟上的檔案 (資料集、程式碼、文件等)。
- 將 Colab 的輸出結果 (模型、圖表、處理後的資料) 儲存到雲端硬碟。
- 與他人共享雲端硬碟上的檔案,方便協作。
本文將介紹如何在 Colab 中掛載 Google 雲端硬碟,以及讀取和寫入 Google Sheets、Excel 和 TXT 這三種常見檔案格式的最實用方法。
掛載 Google 雲端硬碟
在 Colab 中掛載 Google 雲端硬碟有兩種主要方法:
方法一:使用 drive.mount() (簡單快速)
這是最簡單的方法,適合只需要存取 Google Drive 檔案的情況。
from google.colab import drive
drive.mount('/content/drive')
執行這段程式碼後:
- 會出現一個連結,點擊它。
- 在彈出的視窗中選擇您的 Google 帳戶。
- 授予 Colab 存取您 Google 雲端硬碟的權限。
- 複製驗證碼,貼回 Colab 的輸入框中,然後按 Enter。
掛載成功後,您的 Google 雲端硬碟根目錄會出現在 /content/drive/MyDrive。 您可以使用 Linux 檔案路徑語法 (例如 /content/drive/MyDrive/MyFolder/MyFile.txt) 來存取您的檔案。
重要提示: 每次重新啟動 Colab 工作階段時,都需要重新掛載 Google 雲端硬碟。
專業建議: 為了安全起見,建議在程式碼中加入判斷,確認 Google Drive 是否已經掛載,避免重複執行掛載或在未掛載時出錯。
import os
from google.colab import drive
# 確認掛載路徑是否不存在
if not os.path.exists('/content/drive/MyDrive'):
drive.mount('/content/drive')
else:
print("Google Drive is already mounted.")
方法二:使用 auth.authenticate_user() (進階)
如果您需要更精細的權限控制,或者需要存取其他 Google 服務 (例如 Google Sheets API),建議使用此方法。
from google.colab import auth
auth.authenticate_user()
執行這段程式碼後,會出現與 drive.mount() 類似的授權流程。 此方法通常與 Google API 的 Python 客戶端函式庫 (例如 google-api-python-client、gspread) 一起使用。
讀取和寫入檔案
在檔案讀寫的部分,為了程式碼簡潔和通用性,建議直接使用檔案的絕對路徑,而不用再額外使用 cd 或 os.chdir() 切換工作目錄。
Google Sheets
推薦方法: 使用 gspread 函式庫。
安裝:
!pip install gspread
範例程式碼:
import gspread
import pandas as pd
from google.colab import auth
auth.authenticate_user() # 進行使用者驗證
from google.auth import default
# 1. 授權 gspread
creds, _ = default()
gc = gspread.authorize(creds)
# 2. 開啟試算表 (使用試算表 ID 或網址)
# 確保 YOUR_SPREADSHEET_ID 已替換
spreadsheet = gc.open_by_key('YOUR_SPREADSHEET_ID')
# 3. 選擇工作表
worksheet = spreadsheet.sheet1 # 選擇第一個工作表
# 4. 讀取資料 (轉換為 Pandas DataFrame)
data = worksheet.get_all_records()
df = pd.DataFrame(data)
print("成功讀取 Google Sheet 資料:")
print(df.head())
# 5. (可選) 將資料寫入新的工作表
# worksheet.update([df.columns.values.tolist()] + df.values.tolist())
服務帳戶金鑰 (另一種驗證方式):
若不想每次都手動驗證,可使用服務帳戶金鑰自動化授權:
- 前往 Google Cloud Console。
- 建立或選擇一個專案。
- 在「API 和服務」中啟用 Google Sheets API 和 Google Drive API。
- 建立一個「服務帳戶」。
- 為服務帳戶建立金鑰 (JSON 格式) 並下載。
- 將金鑰檔案上傳到您的 Colab 環境或雲端硬碟中。
最重要的一步:無論使用哪種驗證方式,都必須將您的服務帳戶 Email (或您自己的 Google 帳戶 Email) 加入目標 Google 試算表的共用清單中,並給予「編輯者」權限,否則即使有金鑰也無法存取!
Excel 檔案
推薦方法: 使用 pandas 函式庫。
安裝:
!pip install pandas openpyxl
範例程式碼:
import pandas as pd
# 讀取 Excel 檔案
excel_file_path = '/content/drive/MyDrive/path/to/your/file.xlsx'
df = pd.read_excel(excel_file_path, sheet_name='Sheet1') # 讀取指定的工作表
print("成功讀取 Excel 資料:")
print(df.head())
# (可選) 將 DataFrame 寫入 Excel 檔案
output_excel_file_path = '/content/drive/MyDrive/path/to/output/file.xlsx'
# df.to_excel(output_excel_file_path, index=False, sheet_name='Sheet1')
TXT 檔案
推薦方法: 使用 Python 內建的檔案 I/O 功能。
範例程式碼:
# 讀取 TXT 檔案
txt_file_path = '/content/drive/MyDrive/path/to/your/file.txt'
with open(txt_file_path, 'r', encoding='utf-8') as f:
content = f.read()
print("TXT 檔案內容:")
print(content)
# (可選) 寫入 TXT 檔案
output_txt_file_path = '/content/drive/MyDrive/path/to/output/file.txt'
new_content = "Hello from Colab!\nThis is a new line."
# with open(output_txt_file_path, 'w', encoding='utf-8') as f:
# f.write(new_content)
總結
透過本文介紹的方法,您可以輕鬆地在 Colab 中與 Google 雲端硬碟整合,並讀寫 Google Sheets、Excel 和 TXT 檔案。 善用這些技巧,可以讓您的 Colab 專案更具彈性和便利性。 無論是資料分析、機器學習還是其他應用,都能更有效率地進行!