How to store large tuples, lists, and dictionaries in a .txt file, and then assign it to a variable to use them in python code?

Question:

I am currently working on pytests, and for the expected results, which are in form of tuples, or lists are making the pytest classes look clunky.

This is not a duplicate question. In no other solutions they portray for txt file.

For example, the answer to this question for a json file is:

path = "C:\my_file.json"
my_var = json.load(open(path))

Likewise, how to do it for tuples, or lists?

Is storing in a .txt file a good option? If so how to assign the entire context correctly to a variable?

Asked By: fewistle

||

Answers:

For a .txt file you can do something like:

path = 'C:\my_file.txt'
open_file = open(path, 'r')
var = open_file.read() 
Answered By: layman

As juanpa comments below, you should just define your expected results in another module and refer to them through the module to avoid cluttering up your actual test classes.

If this is not an acceptable solution, read on.


You can store your expected results to a txt file, and then use ast.literal_eval to parse it to a python object. Note that your text must be made up entirely of python literals for this to work (you can’t include a variable, e.g.)

Suppose you have an expected_result.txt that looks like so:

['1', 2, (3, 4, 5), {'6': 7}, {8, 9, 10}]
import ast

with open("expected_result.txt") as f:
    e = ast.literal_eval(f.read())

gives the list e = ['1', 2, (3, 4, 5), {'6': 7}, {8, 9, 10}]

Inspecting that object:

print(type(e))
for index, item in enumerate(e):
    print(index, type(item), item)

prints:

<class 'list'>
0 <class 'str'> 1
1 <class 'int'> 2
2 <class 'tuple'> (3, 4, 5)
3 <class 'dict'> {'6': 7}
4 <class 'set'> {8, 9, 10}

Further reading:

Answered By: Pranav Hosangadi
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.