Skip to content Skip to sidebar Skip to footer

How To Read A List Which Is In List Format In A Text File In Python

I have this list in a txt file: [1, 'hello', {'Name': 'Tom'}, [2, 3, 'hello_hello'], (800, 600)] There are an int, a str, a dict, a list and a tuple (not that it was really the ma

Solution 1:

As indicated by @AvinashRaj in the comments, you can use the ast module (ast: Abstract Syntax Trees):

import ast

print ast.literal_eval('[1, "hello", {"Name": "Tom"}, [2, 3, "hello_hello"], (800, 600)]')

Output:

[1, 'hello', {'Name': 'Tom'}, [2, 3, 'hello_hello'], (800, 600)]

This should be the exact result (elem) you are expecting.

Solution 2:

I'd consider it a json.

importjsonmy_list= json.load(my_str_list)

Post a Comment for "How To Read A List Which Is In List Format In A Text File In Python"