pickle.dump(stats, items, outfile) TypeError: an integer is required (got type _io.BufferedWriter)

Posted

技术标签:

【中文标题】pickle.dump(stats, items, outfile) TypeError: an integer is required (got type _io.BufferedWriter)【英文标题】: 【发布时间】:2020-11-13 18:55:18 【问题描述】:
#!Python 3.8.3
#Dungeon Game Similar to dungeons and dragons, turn fight game

import pickle, time, sys, random
filename = "Save_File"

load = input("Would you like to load a save? y/n")
if load == "y":
    try:
        infile = open(filename, "rb")
        pickle.load(infile)
        infile.close()
    except:
        print("It seems you typed your save name wrong. Resart the program to try again")
        pass
        
NameInput = input("Enter Your Characters Name Here To Start Your Journey:")
ClassType = input("What Class Do You Choose? Mage, Healer, Barbarian, Archer, Warrior?")


stats = 
    "Health" : "100",
    "Gold" : "50",
    "Name" : NameInput,
    "ClassType" : ClassType,
    "melee" : "10",
    "defence" : "0"
    
items = 
    "Healing Potion" : "0",
    "Amber" : "0",
    "Amethyst" : "0",
    "Arrows" : "0",
    "Azurite" : "0",
    "Backpack" : "0"
    

outfile = open(filename, "wb")
pickle.dump(stats, items, outfile)
outfile.close()

所以我有这个问题有人知道如何解决吗?错误在标题中。我制作了一款回合制游戏,我将使用保存功能来保存您的进度。有人可以解释一下这个错误以及如何解决它。

【问题讨论】:

顺便说一句,我现在只是保存以检查保存功能是否有效 你能告诉我们你的确切错误是什么吗? 【参考方案1】:

我在另一个问题中回答了这个问题。 Store Python function in JSON

Python 有一个内置的模块名称 marshal 可以处理这个问题。

import marshal, ujson as json

def multiplier(a, b):
    return a * b

x = 
  "x":5,
  "y":4,
  "func" : marshal.dumps(multiplier.func_code)


x = json.dumps(x)
print(x)

然后把它拿回来......

x = json.loads(x)
x = marshal.loads(x['func'])
# maybe save the function name in dict
func = types.FunctionType(x, globals(), "some_func_name") 

print(func(2,4))

【讨论】:

以上是关于pickle.dump(stats, items, outfile) TypeError: an integer is required (got type _io.BufferedWriter)的主要内容,如果未能解决你的问题,请参考以下文章

pickle.dump(模型,pickle_out)| TypeError:无法腌制 _thread._local 对象

pickle.dump()和pickle.load()进行文件操作

pickle.load,pickle.dump构建Coco数据集labels的pickle文件

python文件操作:pickle模块多次dump后出现的读取问题

Python中Pickle模块的dump()方法和load()方法

使用 pickle.dump - TypeError: must be str, not bytes