将数据框作为CSV文件从Google Colab导出到Google Drive

时间:2018-12-22 19:47:43

标签: python csv google-colaboratory drive

我想将数据帧以csv的形式从colab上传到google drive.i尝试了很多但没有运气。我可以上传简单的文本文件,但是csv 我尝试了以下代码。

import pandas as pd
df=pd.DataFrame({1:[1,2,3]})
df.to_csv('abc',sep='\t')
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
uploaded = drive.CreateFile({'title': 'sample.csv', 'mimeType':'csv'})
uploaded.SetContentFile('abc')
uploaded.Upload()

5 个答案:

答案 0 :(得分:7)

不使用!cp命令

from google.colab import drive

  • 将google驱动器安装到Colab Notebook

drive.mount('/drive')

  • 在上传之前,请确保在Google驱动器中创建了文件夹名称

df.to_csv('/drive/My Drive/folder_name/name_csv_file.csv')

答案 1 :(得分:6)

# Import Drive API and authenticate.
from google.colab import drive

# Mount your Drive to the Colab VM.
drive.mount('/gdrive')

# Write the DataFrame to CSV file.
with open('/gdrive/My Drive/foo.csv', 'w') as f:
  df.to_csv(f)

答案 2 :(得分:3)

使用挂载代替pydrive可能会更容易。

from google.colab import drive
drive.mount('drive')

身份验证后,您可以复制csv文件。

df.to_csv('data.csv')
!cp data.csv drive/My\ Drive/

答案 3 :(得分:0)

如果您不想使用熊猫,请执行以下操作:

ProductsModel productsModel = ProductsModel();

Widget build(BuildContext context) {
    return ScopedModel<ProductsModel>(
  model: productsModel,

答案 4 :(得分:0)

如果你想保存在本地,那么你可以使用这个

f.to_csv('sample.csv')
from google.colab import files
files.download("sample.csv")