【问题标题】:How to save a variable in a file? [duplicate]如何将变量保存在文件中? [复制]
【发布时间】:2018-12-03 10:07:21
【问题描述】:

如何在程序中保存值,以便“记住”它们?

【问题讨论】:

  • 请查看pickle模块
  • 我认为this 帖子是您正在寻找的!问候!

标签: python


【解决方案1】:

查看pickle module

这是直接来自文档的示例,

import pickle

# An arbitrary collection of objects supported by pickle.
data = {
    'a': [1, 2.0, 3, 4+6j],
    'b': ("character string", b"byte string"),
    'c': {None, True, False}
}

with open('data.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

import pickle

with open('data.pickle', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)

【讨论】:

  • 但这是为了将变量保存在不同的文件中,不是吗?我想将值保存到程序中的变量中
  • @A.Shah:这样做非常困难,因为这相当于程序修改自己的代码。尽管这样做并非不可能,但它有点麻烦,可能难以调试,并且可能会引入安全问题——即这是一种糟糕的编程习惯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
  • 2016-10-25
  • 1970-01-01
  • 2017-09-29
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
相关资源
最近更新 更多