I'm trying to make a leaderboard function for my game using a .txt file but when extracting lists it converts the tuples into strings
the code i have:
#USER INPUT__________________________________________________________
text=input("input: ")
#READING AND PRINTING FILE__________________________________________
a_file = open("textest.txt", "r")
list_of_lists = []
for line in a_file:
stripped_line = line.strip()
line_list = stripped_line.split()
list_of_lists.append(line_list)
a_file.close()
print(list_of_lists)
#INSERTING STUFF IN THE FILE_________________________________________
with open("textest.txt", "a ") as file_object:
file_object.seek(0)
data = file_object.read(100)
if len(data) > 0 :
file_object.write("\n")
file_object.write(text)
the contents of the file are
['test1', 60]
['play 1', 5080]
['test2', 60]
['test3', 160]
['fake1', 69420]
but the output gives
("['test1', 60]","['play 1', 5080]","['test2', 60]","['test3', 160]","['fake1', 69420]")
CodePudding user response:
Use ast.literal_eval()
to parse the file into lists.
import ast
with open("textest.txt", "r") as a_file:
list_of_lists = [ast.literal_eval(line) for line in a_file]
CodePudding user response:
ast.literal_eval()
safely evaluates an expression node or a string containing a Python literal.
import ast
data = ("['test1', 60]","['play 1', 5080]","['test2', 60]","['test3', 160]","['fake1', 69420]")
[tuple(ast.literal_eval(x)) for x in data]
Output:
[('test1', 60),
('play 1', 5080),
('test2', 60),
('test3', 160),
('fake1', 69420)]