我有一个file.npy文件,想要在Google Colaboratory笔记本中加载它。我已经知道必须从Google Drive加载该文件,但是我不知道如何操作。
欢迎任何帮助。
我有一个file.npy文件,想要在Google Colaboratory笔记本中加载它。我已经知道必须从Google Drive加载该文件,但是我不知道如何操作。
欢迎任何帮助。
使用以下方法将文件上传到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文件。
这是对我有效的方法。希望它对你有所帮助。
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 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'
这就是全部内容!享受吧!