0

I have a text file that looks like this

['M', '>', 'F', 'P', ' ', 'N', 'I', '$', 'F', '\x19', 'J', 'B', 'P', 'T', '%', '<', 'M', 'Q', '>', '\x00', 'I', 'F', 'N', 'J', '\x16', 'X', '\\', 'H']

Its already in a list form. How do i load it into python as a list without it think that all the separators between the sections are actual characters?

user3320350
  • 875
  • 1
  • 6
  • 4
  • 1
    Usually, the _right_ answer to this question is "don't generate files like that, then you won't need to parse them". – abarnert May 01 '15 at 10:56

1 Answers1

1

Read the contents as a string, and use ast.literal_eval to convert it into a Python data structure.

That is:

import ast
with open('datafile.txt') as f:
    data = ast.literal_eval(f.read())
Antti Haapala
  • 117,318
  • 21
  • 243
  • 279
  • or: http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python – Igor May 01 '15 at 10:51
  • I still get ['M', '>', 'F', 'P', ' ', 'N', 'I', '$', 'F', '\x19', 'J', 'B', 'P', 'T', '%', '', '\x00', 'I', 'F', 'N', 'J', '\x16', 'X', '\\', 'H'] as the output. It was supposed to be "M>FP NI$F..." etc. – user3320350 May 01 '15 at 11:07
  • it is a `list`. That is the output you get if you print a list. Please read the [Python tutorial 3.1.3 *Lists*](https://docs.python.org/3/tutorial/introduction.html#lists) – Antti Haapala May 01 '15 at 11:10
  • To convert it to a string, use [`join`](https://docs.python.org/3/library/stdtypes.html?highlight=join#str.join). –  May 01 '15 at 12:11