Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建具有给定名称的空pickle文件?_Python_Pickle - Fatal编程技术网

Python 如何创建具有给定名称的空pickle文件?

Python 如何创建具有给定名称的空pickle文件?,python,pickle,Python,Pickle,我想做以下工作: 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!

我想做以下工作:

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: '.'

谢谢

您可以这样做:

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将一些对象转储到该文件中。转储可能更清楚:

进口 创建pickle并保存数据 打开pickle文件 测试数据 输出
{'Test1':1,'Test2':2,'Test3':3}
真的

第二行的
文件(文件名,“wb”)
是什么?什么错误?发布错误日志。谢谢!我得到了以下错误:文件“AE_PCA.py”,第203行,主要以open(文件名,'wb')作为文件:isDirectoryError:[Errno 21]是一个目录:'/'@Klemen Kolešabtw,不要使用
dict
作为变量名。@Bjoerk谢谢,但我得到的错误与我告诉Klemen的相同
import os
import 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'>