[英]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? 如何重新打开文件并写入新数据而不删除已存储的旧数据?
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')
,默认为后者)。
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.