如何下载在 Colaboratory 工作区中创建的文件?

How to download file created in Colaboratory workspace?

我发现了很多如何将数据上传到 Colaboratory 的提示。

但现在我想做相反的事情 -> 我想下载我在 Colaboratory 工作区中创建的 .csv。

如何操作?

将其保存到 google 驱动器使用 Pydrive

# Install the PyDrive wrapper & import libraries.
# This only needs to be done once in a notebook.
!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

# Authenticate and create the PyDrive client.
# This only needs to be done once in a notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

# Create & upload a file.
uploaded = drive.CreateFile({'title': 'filename.csv'})
uploaded.SetContentFile('filename.csv')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))

使用文件 colab 库

from google.colab import files
files.download('example.txt') 

PS: 使用chrome浏览器

这里是关于如何在 Google Colab 中处理文件的 extensive tutorial。 如果您只想将数据保存为 csv 并在本地下载:

from google.colab import files

# e.g. save pandas output as csv
dataframe.to_csv('example.csv')

# or any other file as usual
# with open('example.csv', 'w') as f:
#   f.write('your strings here')

files.download('example.csv')

试试这个 ipython 功能。 !mkdir data && wget http://file_url/file_name.zip && unzip file.zip -d data/

您可以使用文件管理器面板。

使用 查看 > Table 的内容 显示边栏然后单击 文件 选项卡。 右键单击文件并select 下载.

注意:该过程不寻常,因为浏览器中不会以通常的方式显示下载进度。相反,它在 Colab 中的文件旁边显示为橙色圆圈。只有下载完成后才会出现在浏览器下载中。

在 Firefox 中,最好在下载过程中将选项卡保持在前台,否则可能会失败。

您需要添加这两行:

from google.colab import files
files.download('file.txt')

如果您使用的是 firefox,那么这可能不起作用。 为了完成这项工作:

  1. 从 google.colab 导入文件
  2. 在下一个单元格中,打印任何内容,例如 print('foo').
  3. 打印完成后,擦除打印行并将其替换为:files.download('file.txt')

现在,它将下载。这是我同事告诉我的一个 hacky 解决方案。我不知道为什么它有效!如果你知道为什么,请评论。

有一种更简洁、更简单的方法可以在 firefox 和 chrome 中使用。

点击 > 图标。单击文件。它将显示笔记本中的所有文件和文件夹。左键单击要下载的文件,选择下载,一切顺利。此程序也可以应用于上传file/folder。不过,要上传文件夹,您必须先将其压缩。

在 Firefox 中从 colab 下载 csv 时遇到了同样的问题。 这是一个快速解决方法(每次都对我有用,而且很奇怪)。

假设我已经像这样保存了一个 csv -

from google.colab import files
submission.to_csv('./submission.csv', sep = ',', index = False)

要下载这个,我首先要- 尝试下载一些甚至不存在的文件,这样 colab 就会出错

files.download('submission111111.csv')

然后 运行

files.download('submission.csv')

这是要下载的实际文件。 它对我来说每次都有效,我忍不住笑着找到这个奇怪的把戏。

正在将文件和文件夹移动到 Google 驱动器

  1. 安装 google 驱动器 - 按照屏幕上输出的说明进行操作:
from google.colab import drive
drive.mount('/content/drive')

完成此步骤后,您会在边栏文件管理器中看到名为 drive

的额外文件夹
  1. 使用侧边栏通过拖放方法或使用此命令复制文件(注意,需要确保安装的驱动器上存在指定的文件夹结构):
# Copying folders, format: !rsync -r --progress source_path destination_path
!rsync -r --progress "./model" "/content/drive/My Drive/Colab Notebooks/my-project/model" 

您也可以使用相同的命令将文件从 Google 驱动器移动到笔记本环境,这是在运行时断开连接时备份状态的便捷方式。