简体   繁体   English

Pickle 没有将数据保存到具有格式化字符串名称的文件中

[英]Pickle is not saving data to a file with a formatted string name

I am baffled by the behavior of the code below.我对下面代码的行为感到困惑。 There are two problems;有两个问题; I am not sure whether they are related in some strange way.我不确定它们是否以某种奇怪的方式相关。

The first problem is the more important one.第一个问题是更重要的问题。 The code should save two files containing the same data.该代码应保存两个包含相同数据的文件。 However, test.pkl is about 79 kB whereas the other is empty.然而, test.pkl大约 79 kB,而另一个是空的。 Why is nothing being saved there after the file is created?为什么创建文件后没有保存任何内容?

The second issue I noticed is that the second file is saved as something like ev-w1-n2-2020-12-13-19 without any file extension.我注意到的第二个问题是第二个文件被保存为ev-w1-n2-2020-12-13-19类的东西,没有任何文件扩展名。 What happened to the .pkl ? .pkl发生了什么?

I am using Python 3.8 with pickle 4.0 on Windows 10.我在 Windows 10 上使用 Python 3.8 和泡菜 4.0。

import pickle
import numpy as np
import datetime

n = 100
z = np.zeros((n,n))
with open("test.pkl" , 'wb') as myfile:
    pickle.dump(z, myfile)

filename = "e-v-w%s-n%s-%s.pkl" % (1, 2, datetime.datetime.now().strftime("%Y-%m-%d-%H:%M"))
print(filename)
with open(filename, "wb") as outfile:
    pickle.dump(z, outfile, pickle.HIGHEST_PROTOCOL)

When I print filename , the .pkl appears as it should, by the way.顺便说一下,当我打印filename时, .pkl会按原样出现。

The colon character (":") is not allowed in Windows filepaths, for example this post . Windows 文件路径中不允许使用冒号(“:”),例如这篇文章

Your strftime format includes a colon, which makes it impossible for that path to be written to, and is also presumably the reason why the characters after the colon (suck as the .pkl extension) are missing.您的strftime格式包含一个冒号,这使得该路径无法写入,并且可能也是冒号后面的字符(作为.pkl扩展名)丢失的原因。

Running your code on a Unix platform worked as expected.在 Unix 平台上运行您的代码按预期工作。 Simply change your strftime format to make it compatible with Windows.只需更改您的strftime格式,使其与 Windows 兼容。

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

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