Pickle 和 Unpickle dict w/list 作为值

发布于 2024-12-04 14:43:52 字数 384 浏览 1 评论 0原文

我有一本字典,其中包含一个列表作为值,例如:

numlist = {'Person': ['2342342', '15:05']}

我腌制它。

outfile = open{"log.txt", "wb")
pickle.dump(numlist, outfile)

我把它拆开。

infile = open("log.txt", "rb")
pickle.load(infile)

如何将此二进制数据转换回其原始格式? (以变量“name”为键的字典,以两个项目(用于数字的变量“number”和用于时间的“calltime”变量)作为值的列表)?

I have a dictionary with a list as a value such as:

numlist = {'Person': ['2342342', '15:05']}

I pickle it.

outfile = open{"log.txt", "wb")
pickle.dump(numlist, outfile)

I unpickle it.

infile = open("log.txt", "rb")
pickle.load(infile)

How do I convert this binary data back to it's original format? (a dictionary with the variable 'name' as the key, and the list with two items(a variable 'number' for the number and 'calltime' for the time) as the value)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

高冷爸爸 2024-12-11 14:43:52

好的,让我们尝试一下:

In [22]: import pickle

In [23]: numlist = {'Person': ['2342342', '15:05']}

In [24]: outfile = open("log.txt", "wb")

In [25]: pickle.dump(numlist, outfile)

In [26]: outfile.close()

In [27]: infile = open("log.txt", "rb")

In [28]: pickle.load(infile)
Out[28]: {'Person': ['2342342', '15:05']}

如您所见,我准确地返回了开始时的内容 (numlist)。与您的代码相比,唯一改变的是我在重新打开 outfile 之前关闭它,以确保刷新缓冲区。

OK, let's try it:

In [22]: import pickle

In [23]: numlist = {'Person': ['2342342', '15:05']}

In [24]: outfile = open("log.txt", "wb")

In [25]: pickle.dump(numlist, outfile)

In [26]: outfile.close()

In [27]: infile = open("log.txt", "rb")

In [28]: pickle.load(infile)
Out[28]: {'Person': ['2342342', '15:05']}

As you can see, I got back exactly what I've started with (numlist). The only thing that's changed compared to your code is that I close outfile before re-opening it, to make sure that the buffers get flushed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文