简体   繁体   English

H5py:在写模式下重新打开文件会删除以前的数据

[英]H5py: reopening file in write mode deletes previous data

import h5py
import numpy as np

f = h5py.File('test','w')
f.create_dataset('key1', data = np.array([1,2,3]))
f.create_dataset('key2', data = np.array([4,5,6]))
f.close()

creates the file named test and writes two arrays under key1 and key2 respectively. 创建名为test的文件,并分别在key1和key2下写入两个数组。

However, closing the file object and reopening the file deletes the data previously stored. 但是,关闭文件对象并重新打开文件会删除以前存储的数据。

f = h5py.File('test','w')
f.create_dataset('key1', data = np.array([1,2,3]))
f.close()
f = h5py.File('test','w')
f.create_dataset('key2', data = np.array([4,5,6]))
f.close()

In this case only [4,5,6] is stored under the key key2 . 在这种情况下,仅[4,5,6]存储在键key2

How to reopen the file and write new data without deleting the old data which is already stored? 如何重新打开文件并写入新数据而不删除已存储的旧数据?

Quick answer 快速回答

Change h5py.File('test','w') to h5py.File('test','a') (or h5py.File('test') , which defaults to the latter). h5py.File('test','w')更改为h5py.File('test','a') (或h5py.File('test') ,默认为后者)。

Why 为什么

When you instantiate a h5py.File object, you have to specify a mode as the second parameter. 实例化h5py.File对象时,必须将mode指定为第二个参数。 This must be one of the following: 这必须是以下之一:

  • r Readonly, file must exist r只读,文件必须存在
  • r+ Read/write, file must exist r+读/写,文件必须存在
  • w Create file, truncate if exists w创建文件,如果存在则截断
  • w- or x Create file, fail if exists w-x创建文件,如果存在则失败
  • a Read/write if exists, create otherwise (default) a读/写(如果存在),否则创建(默认)

Using a is a quick fix, but risky if your program doesn't always know whether the file already exists. 使用a是一种快速解决方案,但是如果您的程序并不总是知道该文件是否已经存在,则存在风险。 You can achieve any desired behavior in a less ambiguous way by using the other modes along with file checking. 通过使用其他模式以及文件检查,您可以以不太模糊的方式实现任何所需的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM