【问题标题】:How do I create an empty pickle file with a given name?如何创建具有给定名称的空泡菜文件?
【发布时间】:2019-04-30 17:37:14
【问题描述】:

我想做以下事情:

1- 检查是否存在具有给定名称的 pkl 文件 2-如果没有,则使用该给定名称创建一个新文件 3- 将数据加载到该文件中

if not os.path.isfile(filename):
    with open(filename,"wb") as file:
        pickle.dump(result, file)
else:
    pickle.dump(result, open(filename,"wb") ) 

但是,即使我已经检查了文件是否存在(甚至不应该输入 if !!)给定路径,这也会引发错误:

Traceback (most recent call last):   
with open(filename_i,"wb") as file:
IsADirectoryError: [Errno 21] Is a directory: '.'

谢谢!

【问题讨论】:

  • 第二行的file(filename, "wb") 是什么?
  • 什么错误?发布错误日志。

标签: python pickle


【解决方案1】:

你可以这样做:

import os
import pickle

if not os.path.isfile("test_pkl.pkl"):
    with open("test_pkl.pkl",'wb') as file:
        pickle.dump("some obejct", file)

首先它检查文件是否存在,如果不存在则创建文件(“wb”),然后通过pickle pickle.dump 将一些对象转储给它

【讨论】:

  • 谢谢!我收到以下错误:文件“AE_PCA.py”,第 203 行,以 open(filename,'wb') 作为文件:IsADirectoryError: [Errno 21] Is a directory: '/' @Klemen Koleša
【解决方案2】:

也许这更清楚:

进口

import os
import pickle

创建pickle并保存数据

dict = { 'Test1': 1, 'Test2': 2, 'Test3': 3 }
filename = "test_pkl.pkl"


if not os.path.isfile(filename):
   with open(filename,'wb') as file:
       pickle.dump(dict, file)
   file.close() 

打开泡菜文件

  infile = open(filename,'rb')
  new_dict = pickle.load(infile)
  infile.close() 

测试数据

  print(new_dict)
  print(new_dict == dict)
  print(type(new_dict))

输出

  {'Test1': 1, 'Test2': 2, 'Test3': 3}
  True
  <class 'dict'>

【讨论】:

  • 顺便说一句,不要使用dict作为变量名。
  • @Bjoerk 谢谢,但我遇到了与 Klemen 相同的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多