11

我有file.npy并且我想将它加载到Google Colaboratory Notebook 中。我已经知道我必须从 Google Drive 加载文件,但是我不知道该怎么做。

欢迎任何帮助

4

3 回答 3

17

使用以下内容将您的文件上传到 Colaboratory Notebook:

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在当前目录中看到文件。

这是对我有用的方法。希望能帮助到你。

于 2017-11-15T14:05:36.623 回答
7

实际上,您可以直接上传和下载本地文件。

在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])))
于 2017-11-10T01:41:48.390 回答
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 个子目录,例如(培训、验证和测试):

train_data_dir = dirName + 'training'  
validation_data_dir = dirName + 'validation'  
test_data_dir = dirName + 'test' 

这就对了!享受!

于 2018-03-24T16:25:43.363 回答