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
3
  • 1
    Is it guaranteed that there is only one array with this exact format in the file? Commented Feb 17, 2017 at 14:17
  • This question might help you to get the list from the string: stackoverflow.com/questions/1894269/… Commented Feb 17, 2017 at 14:17
  • Tobias, yes it is. It will always be the same format.With only one Array showing. Commented Feb 17, 2017 at 14:19

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, this seems to do what I want, and a simpe solution. Thanks :)
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(',')]

Comments

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.

3 Comments

But with this solution you wont treat the numbers as int, everything will be considered as string, right?
@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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.