如何在Google Colaboratory中导入和读取shelve或Numpy文件?

11

我有一个file.npy文件,想要在Google Colaboratory笔记本中加载它。我已经知道必须从Google Drive加载该文件,但是我不知道如何操作。

欢迎任何帮助。

3个回答

17

使用以下方法将文件上传到Colaboratory笔记本中:

from google.colab import files
uploaded = files.upload()

接下来,您可以从 uploaded 对象中访问文件内容,然后将其写入文件:

with open("my_data.h5", 'w') as f:
    f.write(uploaded[uploaded.keys()[0]])

如果您运行:

!ls

你将在当前目录中看到my_data.h5文件。

这是对我有效的方法。希望它对你有所帮助。


那对我来说真的很有帮助。谢谢 :) - Abdelwahed

8
实际上,您可以直接上传和下载本地文件。 在I/O示例笔记本中,有本地文件上传/下载以及Drive文件上传/下载的示例。 第一个单元格展示了本地文件上传:
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])))

2

上传包含子文件夹和文件(图片)的文件和文件夹到Colab Google:
请尝试使用此函数将文件和文件夹上传到Colab Google:

from google.colab import files
import zipfile, io, os

    def read_dir_file(case_f):  # case_f = 0 for uploading one File and case_f = 1 for uploading one Zipped Directory
        uploaded = files.upload()    # to upload a Full Directory, please Zip it first (use WinZip)
        for fn in uploaded.keys():
            name = fn  #.encode('utf-8')
            #print('\nfile after encode', name)
            #name = io.BytesIO(uploaded[name])
        if case_f == 0:    # case of uploading 'One File only'
            print('\n file name: ', name)
            return name
        else:   # case of uploading a directory and its subdirectories and files
            zfile = zipfile.ZipFile(name, 'r')   # unzip the directory 
            zfile.extractall()
            for d in zfile.namelist():   # d = directory
                print('\n main directory name: ', d)
                return d
    print('Done!')

1- 上传单个文件:

fileName = read_dir_file(0)

如果您要上传的文件是 .csv 文件,则:

import pandas as pd
df = pd.read_csv(fileName)
df.head()
您可以使用相同的方式阅读任何具有不同格式的文件。 2- 要上传具有子目录和文件的完整目录: 首先使用一个zip压缩目录,然后使用以下命令:
dirName = read_dir_file(1)

然后,您可以将(dirName)作为根目录处理。 举个例子,如果它有3个子目录,分别是 (training, validation 和 test):

train_data_dir = dirName + 'training'  
validation_data_dir = dirName + 'validation'  
test_data_dir = dirName + 'test' 
这就是全部内容!享受吧!

你尝试在一个训练图像目录上尝试过吗?(比如说有数千张用于训练、测试和评估的JPEG图像已经被压缩,所以不会再“压缩”,而且似乎每次打开Colab笔记本时都必须这样做,因为数据并没有被保存下来... Colab似乎没有永久性的“磁盘”。这非常令人恼火,对于机器学习项目,特别是涉及成千上万的图像的深度学习项目,这是不可用的...拷贝数据需要几个小时,而且每次打开笔记本都要这么做。 - Kai
谢谢你的问题,我没有尝试上传如此大量的数据,但我同意你的观点,它需要很长时间才能上传。你有什么线索来解决这个问题吗?谢谢。 - Yasser M
目前我所知道的解决办法是没有的。每次打开笔记本时,你都必须复制数据。我认为(希望)数据可能会持续12小时(这是使用Colab虚拟实例的限制),但我还没有验证过。 - Kai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,