Python:从索引完整的文件导入数组

时间:2017-02-27 19:04:55

标签: python arrays fopen

我有一个文件,我想将其导入数组,但每个条目都作为索引,所以我可以调用每个特定的文件。

文件(testing_array.txt):

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

脚本:

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

输出:

["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

我已经为每个索引的每个条目尝试了一个for循环,但没有成功.insert。我刚开始3天前编写python脚本,所以如果我忽略了一些基本的东西,我会道歉。任何帮助将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:4)

尝试使用json序列化程序(它与列表的语法相同)。

import json

my_list = json.loads('["zero", "one", "two", "three", "four", "five"]')

答案 1 :(得分:3)

您也可以删除方括号并将该行拆分为列表。

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