Skip to content Skip to sidebar Skip to footer

Python: Read File With List As List

I have placed a list in a text file. I want python to read the text file and return the contents as a list. However, it is instead reading the content as a string: Text file: ['a',

Solution 1:

Use ast.literal_eval to literally evaluate the contents of file as is written though really a string:

data = ast.literal_eval(open('data.txt').read()) # create file, read contents, evaluate

Solution 2:

If you just have the same format the quickest way would be just to strip and split:

with open('file.txt') as f:
    print(f.readline().translate(None,"'[]\n").split(","))
    ['a', 'b', 'c']

Post a Comment for "Python: Read File With List As List"