I'm reading, updating and writing the following single line of data to a separate fruit.txt file, in this specific structure and format:
[["Peach",0,0,0], ["Banana",0,0,0], ["Apple",0,0,0], ["Pear",0,0,0], ["Mango",0,0,0], ["Orange",0,0,0], ["Apricot",0,0,0]]
When I do this at the start of the Python file
with open("fruit.txt") as file:
fruit = file.read()
It correctly assigns the data in fruit.txt to the fruit var. When I print(fruit), it even looks like the intended nested list.
However, when I come to query fruit var e.g. dynamically changing the 0's via other functions, or when I try to sort the nested list, or do anything to alter the data, it always returns various errors. It's as though when it sets the fruit var to the data from the file, it doesn't recognise it as a nested list, but more a string. So therefore I can't operate on that list.
If however I do:
with open("fruit.txt") as file:
fruit_count = file.read()
fruit = eval(fruit_count)
Then the fruit var behaves fine - values update and it writes back to the file ready for further use etc.
I understand eval is theoretically evil (or at least should be avoided under most circumstances) unless you trust the data source (which I do in this instance). But I'm just wondering if there's a different solution?
Ideally I don't want to use any additional modules e.g. ast.literal_eval