python四种逐行读取文件_Colab读写外部文件的四种方式

本文介绍了在Google Colab上如何与本地文件、Google Drive、Google Sheet和Google Cloud Storage进行交互,包括上传、下载文件以及使用PyDrive连接Google Drive。
摘要由CSDN通过智能技术生成

众所周知,Google Colab是Google提供的运行在云端的jupyter notebook环境。里面集成了许多著名的机器学习python库。由于这个环境是运行在Google虚拟机上的,显然与自己的PC不在一个文件系统。那么怎么与我们自己的文件交互呢?

Colab文档里提供了四种方式,分别是:

从本地直接上传

连接Google Drive

连接Google Sheet

连接Google Cloud Storage

下面就来分别描述。

1.与本地文件交互

从本地直接上传

files.upload() 返回一个由我们上传的所有文件构成的一个字典。 这个字典的key是文件名, 这个字典的value是我们上传的文件的data。

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])))

从Colab下载文件到本地

from google.colab import files

with open('example.txt', 'w') as f:

f.write('some content')

files.download('example.txt')

2.连接Google Drive

这里官方有提供了许多种方法。这里我就挑一种介绍了,有兴趣的可以点进这个链接进去看。

这里只介绍使用PyDrive的方法。PyDrive是google-api-python-client的包装库,简化了许多常见的Google Drive API任务。

!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. 验证身份并创建pydrive客户端.

auth.authenticate_user()

gauth = GoogleAuth()

gauth.credentials = GoogleCredentials.get_application_default()

drive = GoogleDrive(gauth)

# PyDrive 参考:

# https://gsuitedevs.github.io/PyDrive/docs/build/html/index.html

# 2. 创建并上传一个文本文档.

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. 通过id访问文件并输出它的内容.

downloaded = drive.CreateFile({'id': uploaded.get('id')})

print('Downloaded content "{}"'.format(downloaded.GetContentString()))

原文链接:https://blog.csdn.net/Zserendipity/article/details/106524795

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值