[英]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.