files.upload
returns a dictionary of the files which were uploaded.
The dictionary is keyed by the file name, the value is the data which was uploaded.
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
!ls
import pandas as pd
df = pd.DataFrame([1,2,3])
df
df.to_csv('new_file.txt')
!ls
files.download('new_file.txt')
인증번호를 입력하여 현재 가상 머신을 자신의 구글 드라이브와 연결시킬 수 있다.
from google.colab import drive
drive.mount('/gdrive')
!ls /gdrive/My\ Drive/Colab\ Notebooks/data
accidents = pd.read_csv('/gdrive/My Drive/Colab Notebooks/data/accidents.txt', delimiter='\t')
accidents
!ls /gdrive/My\ Drive/Colab\ Notebooks/data
accidents.to_csv('/gdrive/My Drive/Colab Notebooks/data/new_file_accidents.txt')
!ls /gdrive/My\ Drive/Colab\ Notebooks/data
The example below shows 1) authentication, 2) file upload, and 3) file download. More examples are available in the PyDrive documentation
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# PyDrive reference:
# https://gsuitedevs.github.io/PyDrive/docs/build/html/index.html
# 2. Create & upload a file text file.
uploaded = drive.CreateFile({'title': 'Sample upload.txt'})
uploaded.SetContentString('Sample upload file content')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))
# 3. Load a file by ID and print its contents.
downloaded = drive.CreateFile({'id': uploaded.get('id')})
print('Downloaded content "{}"'.format(downloaded.GetContentString()))
with open('/gdrive/foo.txt', 'w') as f:
f.write('Hello Google Drive!')
!cat /gdrive/foo.txt
The first step is to authenticate.
from google.colab import auth
auth.authenticate_user()
Now we can construct a Drive API client.
from googleapiclient.discovery import build
drive_service = build('drive', 'v3')
With the client created, we can use any of the functions in the Google Drive API reference. Examples follow.
# Create a local file to upload.
with open('/tmp/to_upload.txt', 'w') as f:
f.write('my sample file')
print('/tmp/to_upload.txt contains:')
!cat /tmp/to_upload.txt
# Upload the file to Drive. See:
#
# https://developers.google.com/drive/v3/reference/files/create
# https://developers.google.com/drive/v3/web/manage-uploads
from googleapiclient.http import MediaFileUpload
file_metadata = {
'name': 'Sample file',
'mimeType': 'text/plain'
}
media = MediaFileUpload('/tmp/to_upload.txt',
mimetype='text/plain',
resumable=True)
created = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print('File ID: {}'.format(created.get('id')))
After executing the cell above, a new file named 'Sample file' will appear in your drive.google.com file list. Your file ID will differ since you will have created a new, distinct file from the example above.
# Download the file we just uploaded.
#
# Replace the assignment below with your file ID
# to download a different file.
#
# A file ID looks like: 1uBtlaggVyWshwcyP6kEI-y_W3P8D26sz
file_id = 'target_file_id'
import io
from googleapiclient.http import MediaIoBaseDownload
request = drive_service.files().get_media(fileId=file_id)
downloaded = io.BytesIO()
downloader = MediaIoBaseDownload(downloaded, request)
done = False
while done is False:
# _ is a placeholder for a progress object that we ignore.
# (Our file is small, so we skip reporting progress.)
_, done = downloader.next_chunk()
downloaded.seek(0)
print('Downloaded file contents are: {}'.format(downloaded.read()))
!pip install --upgrade -q gspread
Next, we'll import the library, authenticate, and create the interface to sheets.
from google.colab import auth
auth.authenticate_user()
import gspread
from oauth2client.client import GoogleCredentials
gc = gspread.authorize(GoogleCredentials.get_application_default())
Below is a small set of gspread examples. Additional examples are shown on the gspread Github page.
sh = gc.create('A new spreadsheet')
After executing the cell above, a new spreadsheet will be shown in your sheets list on sheets.google.com.
# Open our new sheet and add some data.
worksheet = gc.open('A new spreadsheet').sheet1
cell_list = worksheet.range('A1:C2')
import random
for cell in cell_list:
cell.value = random.randint(1, 10)
worksheet.update_cells(cell_list)
After executing the cell above, the sheet will be populated with random numbers in the assigned range.
We'll read back to the data that we inserted above and convert the result into a Pandas DataFrame.
(The data you observe will differ since the contents of each cell is a random number.)
# Open our new sheet and read some data.
worksheet = gc.open('A new spreadsheet').sheet1
# get_all_values gives a list of rows.
rows = worksheet.get_all_values()
print(rows)
# Convert to a DataFrame and render.
import pandas as pd
pd.DataFrame.from_records(rows)
Designed by sketchbooks.co.kr / sketchbook5 board skin
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5