我正在写一个程序,在这个程序中,我想在外部文件中读写具有不同数据类型的特定变量。
在尝试了几个不同的模块后,我得到的最接近的方法是使用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 "", line 1, in
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.
如果觉得《python代码读取外部变量_在Python中从外部文件中写入和读取特定的变量》对你有帮助,请点赞、收藏,并留下你的观点哦!