如何用Python从Google Drive访问本地文件?Colab环境实现方法问询
Hey there! Let's break down how to access files in Google Colab—both from your linked Google Drive and directly from your local computer's disk. Here are practical, step-by-step solutions:
Colab makes it easy to mount your Google Drive directly into the cloud environment, so you can access files just like you would on your local machine.
Step 1: Mount your Drive
Run this code snippet to initiate the mounting process:
from google.colab import drive drive.mount('/content/drive')
When you run this, a pop-up will appear with a link. Click it, sign in to your Google account, copy the authorization code, and paste it back into the Colab cell. Once done, your Drive will be mounted at /content/drive/.
Step 2: Access your files
Now you can reference your Drive files using their full path. For example, if you have a CSV file in your Drive's Data folder, you can read it like this:
import pandas as pd # Replace with your actual file path df = pd.read_csv('/content/drive/MyDrive/Data/sample_data.csv') print(df.head())
Since Colab runs in the cloud, you can't directly "browse" your local disk like a regular desktop Python script—but there are two simple ways to work with local files:
Option 1: Use the built-in file upload widget
This is perfect for small to medium-sized files:
from google.colab import files # Trigger the file upload dialog uploaded = files.upload()
A file picker will open on your local computer. Select the file you want to upload, and it will be saved to Colab's temporary workspace. To read it (e.g., a CSV), use:
import pandas as pd import io # Replace 'sample.csv' with your uploaded file's name df = pd.read_csv(io.BytesIO(uploaded['sample.csv'])) print(df.head())
Option 2: Use Colab's Local Runtime (for direct disk access)
If you need to repeatedly access local files without uploading them every time, enable Colab's local runtime:
- Click the "Connect" button in the top-right corner of Colab.
- Select "Connect to local runtime".
- Follow the prompts to install the Colab local runtime plugin on your computer.
Once connected, you can access local files using their regular file paths, just like in a desktop Python script:
import pandas as pd # Replace with your local file path (Windows/macOS/Linux paths work) df = pd.read_csv('C:/Users/YourName/Documents/local_data.csv') # For macOS/Linux: '/Users/YourName/Documents/local_data.csv' print(df.head())
Note: This requires your local machine to stay connected while using Colab.
内容的提问来源于stack exchange,提问作者mohamed_abdullah

