Python:从文件导入数组,其中包含索引

2024-04-26 12:11:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件,我想导入到一个数组中,但有一个索引,所以我可以调用每个具体的项目。你知道吗

文件(测试)_数组.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脚本,所以如果忽略了一些基本内容,我很抱歉。任何帮助都将不胜感激,谢谢。你知道吗


Tags: 文件项目txt脚本地址数组testingarray
2条回答

尝试使用json序列化程序(这与列表的语法相同)。你知道吗

import json

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

也可以删除方括号并将行拆分为列表。你知道吗

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

相关问题 更多 >