在Python中从外部文件中写入和读取特定变量

时间:2018-06-07 19:04:41

标签: python pickle

我正在编写一个程序,我希望从外部文件读取和写入具有不同数据类型的特定变量。 在尝试几个不同的模块后,我最接近的是使用泡菜。 Pickle看起来很棒,因为它了解不同的数据类型,但它不足,因为我理解它从顶部读取行,而不是能够通过名称调用特定变量,因为您可以从外部.py文件。

如果您编写新变量或更改现有变量,此模块和其他模块似乎也会覆盖整个文件,因此如果您实际上只想更改其中一个数据,则必须重写所有数据。

请参阅下面的代码示例。对于长代码,我很抱歉,我只想彻底解释一下。

在这个特定的程序中,文件是否具有人类可读性并不重要。 任何人都可以指出我可以处理这个问题的模块的方向,或者告诉我我可能做错了什么?

import pickle

variable1 = "variable1"
variable2 = "variable2"

pickle_out = open("db.pkl","wb")
pickle.dump(variable1, pickle_out)
pickle.dump(variable2, pickle_out)
pickle_out.close()

#So I'll load the variables in again

pickle_in = open("db.pkl", "rb")
variable1 = pickle.load(pickle_in)
variable2 = pickle.load(pickle_in)
print(variable2)
variable2

#Everything good so far.
#But let's say I only want to load variable2 because I can't remember which 
#line it was written on.

pickle_in = open("db.pkl", "rb")
variable2 = pickle.load(pickle_in)
print(variable2)
variable1

#Also, if I'd like to update the value of variable1, but leave the other 
#variables untouched, it wouldn't work as it would just overwrite the whole 
#file.

#Let's say I've loaded in the variables like at the line 17 print statement.

variable1 = "variable1_new"
pickle_out = open("db.pkl","wb")
pickle.dump(variable1, pickle_out)
pickle_out.close()
pickle_in = open("db.pkl", "rb")
variable1 = pickle.load(pickle_in)
variable2 = pickle.load(pickle_in)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
EOFError: Ran out of input

print (variable1)
variable1_new

#So the value of variable1 is correct, but variable2 is no longer in the 
#pickle-file as the whole file was overwritten.

1 个答案:

答案 0 :(得分:0)

根据您对存储的数据相对简单的评论,JSON文件可能更容易使用。

考虑以下文件 config.json

{
    "str_var": "Somevalue1",
    "list_var": ["value2", "value3"],
    "int_var": 1,
    "nested_var": {
        "int_var": 5
    }
}

现在您可以阅读并使用以下值

import json

# With statement will close the file for us immediately after line 6
with open("config.json", "r") as config_file:
    # Load the data from JSON as a Python dictionary
    config = json.load(config_file)

# See all top level values
for key, value in config.items():
    print(key, ":", value, "Type", type(value))

# Use individual values
print(config["str_var"])
print(config["list_var"][0])
print(config["nested_var"]["int_var"])

# Do something constructive here
...

# Update some values (e.g. settings or so)
config["str_var"] = "Somevalue2"
config["int_var"] = 5
config["list_var"].append("value4")

# Write the file
json.dump(config, open("config.json", "w"), indent=4, sort_keys=True)

导致以下JSON文件:

{
    "int_var": 5,
    "list_var": [
        "value2",
        "value3",
        "value4"
    ],
    "nested_var": {
        "int_var": 5
    },
    "str_var": "Somevalue2"
}

这允许您例如加载这样的配置文件,你可以自由地使用它中的任何值,不需要知道索引。 希望这能让您了解如何使用JSON处理数据。