1

I have a file that I'd like to import into an array but have each entry as an index so I can call each specific one.

File(testing_array.txt):

["zero", "one", "two", "three", "four", "five"]

Script:

f = open('testing_array.txt').read()
array = [f]
print (array[0])
print (array[1])

Output:

["zero", "one", "two", "three", "four", "five"]
Traceback (most recent call last):
  File "testing_array.py", line 4, in <module>
    print (array[1])
IndexError: list index out of range

I've tried a for loop unsuccessfully to .insert each entry for each index. I just started scripting python 3 days ago so I apologize if I'm overlooking something basic. Any help would be appreciated, thanks.

6
  • Sounds like you're looking for eval(). Do not use eval() in production code. It's very dangerous and especially for untrusted input like files. Commented Feb 27, 2017 at 19:07
  • After array = [f] add array = array[0] and tell me if that works please Commented Feb 27, 2017 at 19:07
  • @LeonZ., that would probably cause "[" and '"' to be output, since those are the first and second characters in the file respectively. Commented Feb 27, 2017 at 19:10
  • @Kevin You're probably right, just wanted to make sure he's really got a string within an array, then take it from there Commented Feb 27, 2017 at 19:13
  • @LeonZ. How about type(f) then? Commented Feb 27, 2017 at 19:22

2 Answers 2

4

Try with the json serializer (it's the same syntax for a list).

import json

my_list = json.loads('["zero", "one", "two", "three", "four", "five"]')
Sign up to request clarification or add additional context in comments.

1 Comment

Jeez that was really easy. Thanks for the help!
3

You can also remove the square braces and split the line into list.

>>> line = '["zero", "one", "two", "three", "four", "five"]'
>>> line.strip("[]").split(",")
['"zero"', ' "one"', ' "two"', ' "three"', ' "four"', ' "five"']

Comments

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.