Domanda

Hiya i have made a program that stores the player name and strength..Here is the code:

data = {
    "PLAYER":name2,
    "STRENGTH":str(round(strength, 2)),

}


with open("data2.txt", "w", encoding="utf-8") as file:
   file.write(repr(data))
file.close()

So this stores the data so what to i do if i wanna append/change the value after a certain action usch as a 'BATTLE'

Is it possible the get the variable of 'STRENGTH' and then change the number?

At the moment to read data from the external file 'DATA1.txt'i am using this code:

with open("data1.txt", "r", encoding="utf-8") as file:
   data_string = file.readline()
   data = eval(data_string)
   # (data["STRENGTH"])
   S1 = (float(data["STRENGTH"]))
file.close()

Now i can do something with the variable --> 'S1'

Here is the external text file 'data1.txt'

{'PLAYER': 'Oreo', 'STRENGTH': '11.75'}

... But i wanna change the strength value after a "battle" many thanks

È stato utile?

Soluzione

Maybe you're not understanding Python dict semantics?

Seems to me you're doing a lot of unnecessary things like S1 = (float(data['STRENGTH'])) to try to manipulate and change values when you could be doing really simple stuff.

>>> data = {'PLAYER': 'Oreo', 'STRENGTH': '11.75'}
>>> data['STRENGTH'] = float(data['STRENGTH'])
>>> data
{'PLAYER': 'Oreo', 'STRENGTH': 11.75}
>>> data['STRENGTH'] += 1
>>> data
{'PLAYER': 'Oreo', 'STRENGTH': 12.75}

Maybe you should give Native Data Types -- Dive Into Python 3 a read to see if it clears things up.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top