When you're reading files, Python automatically transforms text file's contents to a list of strings. If you use readlines()
for example, you will create a list of strings, each string from that list being a single line of text from your text file.
Python by itself cannot convert string to a list, what you could do is use ast module, then use ast.literal_eval()
function to transform input string to actual data type, note that the string has to be a correct Python data type (list, set, tuple or dictionary), if it's not the interpreter will raise an exception.
ast.literal_eval() function takes any string as parameter.
Example:
import ast
with open('myfile.txt', 'r') as f:
f_contents = f.readlines()
lists = []
for line in f_contents:
lists.append(ast.literal_eval(line))
This piece of code will:
- Open your text file and read contents
- Each line of text inside the file will be added as an string to
f_conents
list
- Create an empty list of lists, this will contain all valid lists from your
f_contents
list
- For loop that will read through every line of text from
f_contents
and convert it from a string to a proper Python list using ast.literal_eval()
EDIT: Forgot to mention, there's also eval function as mentioned by another answer, however eval()
is considered to be unsafe. ast.literal_eval()
accepts only strings that are identical to a data type in Python, it will throw an exception if input is not a list, dict or tuple; where eval can interpret any command whether it's malicious or not, it's functionality can be abused so it's recommended to not use with user input.