首页 > 解决方案 > 在 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.

标签: pythonpickle

解决方案


根据您对存储的数据相对简单的评论,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 处理数据。


推荐阅读