首页 > 解决方案 > 将元素推送到存储在 Julia 中的 jld2 文件中的数组中

问题描述

我试图将一个元素推送到一个已经存储在 .jld2 文件中的数组中,但是在关闭文件并再次读取它之后,该数组没有更新。

using JLD2

jldopen("example.jld2", "w") do file
    file["mygroup/mystuff"] = [1,2]
end

jldopen("example.jld2", "a+") do file
    push!(file["mygroup"]["mystuff"], 3)
    println(file["mygroup"]["mystuff"])
    # The array should be updated to [1,2,3], and it is also working up to here
end

jldopen("example.jld2", "r") do file
    println(file["mygroup"]["mystuff"][3])
    # I got BoundsError here, for when I am reading the array again, it becomes [1,2] again
    # as if it were never updated.
end

那么我应该如何将元素推送到存储在 .jld2 文件中的数组中呢?

标签: arraysjulia

解决方案


我怀疑这与 python 的 Shelve 存在相同的潜在问题;例如,请参阅https://docs.python.org/3.5/library/shelve.html#example(代码中有关写回的部分)。

实际上,您不能追加/推送!,如果您希望更改持续存在,则应该完全替换该条目的内容。更新:抱歉,api 不清楚,但似乎你不能以这种方式覆盖组。(没有适用于s 的delete!方法或类似方法)。JLD2.Group

因此,虽然您可以将新的组和变量“附加”到 JLD2 文件中,但可能无法以您尝试执行的方式“更新”一个,并且最好从头开始读取文件并重新创建更新的文件。


推荐阅读