2

I have a file with an array written in it, like:

[1, 2, 3, 4, 5, 6, 7]

How can I read it and get the array in a variable with python? So far what happens is that I just get the string.

def get_data():
     myfile = open('random_array.txt', 'r')
     data = myfile.read().replace('\n', '')
     return data
Gonçalo
  • 144
  • 11
  • 1
    Is it guaranteed that there is only one array with this exact format in the file? – Tobias G Feb 17 '17 at 14:17
  • This question might help you to get the list from the string: http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python – dgeorgiev Feb 17 '17 at 14:17
  • Tobias, yes it is. It will always be the same format.With only one Array showing. – Gonçalo Feb 17 '17 at 14:19

3 Answers3

2

If the format is always like that, one way is to use json.loads:

>>> s = "[1,2,3,4]"
>>> import json
>>> json.loads(s)
[1, 2, 3, 4]

This has the advantage that you can use any space between the commas, you can use floats and ints in the text, and so on.

So, in your case you could do this:

import json

def get_data():
    with open("random_array.txt", "r") as f:
        return json.load(f)
csl
  • 10,937
  • 5
  • 57
  • 89
1

In this particular case it is better to use the json module, as it seems your array uses the same format, but in general you can do something like this:

def get_data(filename):
     with open(filename, 'r') as f:
        return [int(x) for x in f.read().strip('[]\n').split(',')]
farsil
  • 955
  • 6
  • 19
0

This should do the trick:

def get_data():
    myfile = open('random_array.txt', 'r')
    data = myfile.read().strip()
    data = data[1:len(data)-1]
    splitted = data.split(", ")
    return splitted

This removes the beginning and trailing "[]" and then splits the string on each ", ", leaving you with an array of strings that are exactly the numbers.

Tobias G
  • 583
  • 2
  • 10
  • 1
    But with this solution you wont treat the numbers as int, everything will be considered as string, right? – Gonçalo Feb 17 '17 at 14:24
  • @GonacFaria yes that's true, but for the simple sake of parsing the data, that should be enough. You could then convert the individual elements of the array via `int(data[i])`. But yes indeed, the json-parser method is more elegant. – Tobias G Feb 17 '17 at 14:26
  • Indeed it is more elegant and a lot simplier. I didn't want to parse the string, but looking for a way to interpreter it. – Gonçalo Feb 17 '17 at 14:29