2

I'm reading in lines of data from a file in this format:

['A', 'B', 'C', 'D', 'E']
['1', '2', '3', '4', '5']

...etc

However, when I do type(dataInput[0]), it tells me it's from type string. Although it looks like a list with the brackets and all. How can i make dataInput[0] directly into a list instead of string?

Here's some code:

fobj = open(selectedCase, 'r').read()
dataInput = re.split('\n', fobj)

I've seen threads such as: How to convert comma-delimited string to list in Python? However that example doesn't have brackets in the string.

Community
  • 1
  • 1

4 Answers4

5

Use ast.literal_eval() to turn those strings into Python lists:

import ast

dataInput = [ast.literal_eval(line) for line in fobj.splitlines()]

Demo:

>>> import ast
>>> result = ast.literal_eval("['A', 'B', 'C', 'D', 'E']")
>>> type(result)
<class 'list'>
>>> result
['A', 'B', 'C', 'D', 'E']

You might want to use the file object as a context manager, to have Python close it again explicitly:

with open(selectedCase) as infh:
    dataInput = [ast.literal_eval(line) for line in infh]

This uses the file object as an iterator as well, the loop will be given one line at a time from the file.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

I may be missing something, but if your data is clean can't you just do:

In [1]: x = "['a','b']"

In [2]: y = eval(x)

In [3]: y
Out[3]: ['a', 'b']

In [4]: type(y)
Out[4]: list
AlG
  • 14,697
  • 4
  • 41
  • 54
  • 1
    I don't think you're missing anything besides the caveat you already added -- the input might not be clean, and over time it can be tricky to keep track of the assumption that it must be. `eval` can easily be disastrous if the input is something like `os.system('rm -rf /blah')`. Since `ast.literal_eval` exists there's no good reason to make the assumption. – svk Dec 12 '13 at 12:37
0

First of all, if the files are really in the format you have specified, you could use readlines to have strings of the line.

If you don't want to eval the content in the file (because you don't trust the source, for example), you could then split by the comma char and strip away the brackets and quotes. Additionally, if you want to check whether or not you have numbers or strings by using string's isxyz methods, like isdigit

wonderb0lt
  • 2,035
  • 1
  • 23
  • 37
0

Here is my approach:

with open('f.txt', 'r') as f:
    # The strip function gets rid of whitespace at the end of a line
    defaultInput = [eval(var.strip()) for var in f]  # A list comprehension

    print defaultInput[0]
    print type(defaultInput[0])
    print defaultInput[1]
    print type(defaultInput[1])

Output:

['A', 'B', 'C', 'D', 'E']
<type 'list'>
['1', '2', '3', '4', '5']
<type 'list'>

Where f.txt is:

['A', 'B', 'C', 'D', 'E']
['1', '2', '3', '4', '5']
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199