1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python代码读取外部变量_在Python中从外部文件中写入和读取特定的变量

python代码读取外部变量_在Python中从外部文件中写入和读取特定的变量

时间:2024-05-16 14:54:08

相关推荐

python代码读取外部变量_在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 "", 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.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。