[英]Write and read specific variables from external file in Python
我正在编写一个程序,我想在该程序中从/向外部文件读取和写入具有不同数据类型的特定变量。 在尝试了几个不同的模块之后,我得到的最接近的结果是使用pickle。 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.
根据您的评论,即所存储的数据相对简单,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处理数据的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.