Writing a list of tuples in a text file and replaying in a list


How do I write a list of tuples to a text file and read them back into the original list format?

My code gives:

["(50, 'AAA')\n", "(40, 'BBB')\n", "(30, 'CCC')\n", "(20, 'DDD')\n", "(10, 'EEE')\n"]

My code:

file = open("x.txt", "w")
default_scores = [(10, "EEE"), (20, "DDD"), (30, "CCC"), (40, "BBB"), \
                  (50, "AAA")]
default_score_strings = []
for entry in default_scores:
    default_score_strings.append(str(entry) + "\n")

file = open("x.txt", "r")
lines = file.readlines()


If you want to write a data-structure to a file and get it back (without mixing it with other contents) you can use (de)serialization with pickle:

import pickle
pickle.dump(default_scores, open('tuple.dump', 'wb'))
retreived_default_scores = pickle.load(open('tuple.dump', 'rb'))

UPDATE: If this is the challenge where pickling is not expected, then it can be done this way:

import ast

ds=[(10, "EEE"), (20, "DDD"), (30, "CCC"), (40, "BBB"), \
                  (50, "AAA")]
fname = 'practice.txt'

with open(fname, 'w') as f:

with open(fname, 'r') as f:
    retreived_ds = ast.literal_eval(f.read())

print(ds == retreived_ds)# True

Further update:

OPs comment imply that this is a practice question in string processing for beginners where use of tools like pickle is not allowed. Then, so are eval statements. In that case:

ds=[(10, "EEE"), (20, "DDD"), (30, "CCC"), (40, "BBB"), \
                  (50, "AAA")]
fname = 'practices.txt'

with open(fname, 'w') as f:

with open(fname, 'r') as f:
    ds_string = f.read()

retreived_ds = []
i = 0
ds_string = ds_string.strip()[1:-1]
while(i < len(ds_string)):
    if ds_string[i] == '(':
        end_index = ds_string[i+1:].index(')') + i
        first, second = ds_string[i+1: end_index].split(',')
        retreived_ds.append((int(first), second.strip().replace("'", "")))
        i = end_index + 1
    i = i + 1

print(retreived_ds == ds)#True