treatyoself
treatyoself

Reputation: 83

Reading a list of tuples from a text file in python

I am reading a text file and I want to read a list of tuples so that I can add another tuple to it in my program and write that appended tuple back to the text file.

Example in the file [('john', 'abc')] Want to write back to the file as [('john', 'abc'), ('jack', 'def')]

However, I whenever I keep writing back to the file, the appended tuple seems to add in double quotes along with square brackets. I just want it to appear as above.

Upvotes: 1

Views: 1938

Answers (2)

hygull
hygull

Reputation: 8740

You can write a reusable function which takes 2 parameters file_path (on which you want to write tuple), tup (which you want to append) and put your logic inside that. Later you can supply proper data to this function and it will do the job for you.

Note: Don't forget to read the documentation as comments in code

tuples.txt (Before writing)

[('john', 'abc')]

Code

def add_tuple_to_file(file_path, tup):
    with open(file_path, 'r+') as f:
        content = f.read().strip() # read content from file and remove whitespaces around
        tuples = eval(content)     # convert string format tuple to original tuple object (not possible using json.loads())
        tuples.append(tup)      # append new tuple `tup` to the old list

        f.seek(0)               # After reading file, file pointer reaches to end of file so place it again at beginning 
        f.truncate()            # truncate file (erase old content)
        f.write(str(tuples))    # write back the updated list

# Try
add_tuple_to_file("./tuples.txt", ('jack', 'def'))

tuples.txt (After writing back)

[('john', 'abc'), ('jack', 'def')] 

References

Upvotes: 1

user5386938
user5386938

Reputation:

You can use ast.literal_eval to get the list object from the string.

import ast

s = "[('john', 'abc')]"
o = ast.literal_eval(s)
print(repr(o)==s)
o.append(('jack', 'def'))
newstr = repr(o)
print(newstr)

Here it is in action.

Upvotes: 1

Related Questions