Python“r+”模式在使用 Pickle 库编写后不读取任何内容

问题描述 投票:0回答:1

我有一个文件,我想从中读取列表,然后使用 pickle 库向其中写入更新的列表。但之后它不会从文件中读取任何内容。我尝试过使用其他人的例子,甚至复制粘贴一些,但我无法让它工作。

我正在使用 Windows 10,并且知道类似问题中提到的 bug。我从这些问题中得到的解决方案是在编写之前添加

f.seek(f.tell())
,但是当我使用 pickle 库编写时这不起作用。

这是我所拥有的:

import pickle

with open("data.bin", "r+b") as file:
    temp_data = pickle.load(file)
    temp_data.append("test")
    file.seek(file.tell())
    pickle.dump(temp_data, file)

with open("data.bin", "rb") as file:
    print(pickle.load(file))
    # prints empty list

如果我分开读写,那么它确实有效。但我应该可以使用

r+
,对吗? (我还用常规文本文件尝试了所有这些,以防它与二进制模式有关,但我得到了相同的结果。)

import pickle

temp_data = []

with open("data.bin", "rb") as file:
    temp_data = pickle.load(file)

with open("data.bin", "wb") as file:
    temp_data.append("test")
    pickle.dump(temp_data, file)

with open("data.bin", "rb") as file:
    print(pickle.load(file))
    # prints ['test']

有谁知道为什么会发生这种情况,还是我只需要单独做?

python python-3.x windows pickle read-write
1个回答
0
投票

您只想在需要时保留文件句柄,因此,如果我将代码更改为以下内容,我发现它完全按照您的预期进行:加载文件,修改数据,写回出来,然后当您(重新)加载它时,您会得到新数据:

mport pickle
import os.path
import random
 
fname = "data.bin"
data = ["test"]
 
# Create a file if it's not there, for testing purposes
if not os.path.isfile(fname):
    with open(fname, "wb") as file:
        pickle.dump(data, file)
 
# Read in our file
with open("data.bin", "r+b") as file:
    data = pickle.load(file)
 
# Update our data and write it back out
print("loaded:", data)
data.append(f"test{random.random()}")
print("updated:", data)
with open("data.bin", "r+b") as file:
    pickle.dump(data, file)
 
# And then let's just read it back in:
with open("data.bin", "rb") as file:
    updated_data = pickle.load(file)
    print("after 'reloading':", updated_data)
© www.soinside.com 2019 - 2024. All rights reserved.