简体   繁体   中英

convert a list of strings to tuples?

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]")

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]

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM