IndexError: list index out of range
回答済みHi,
i want to read data from a text.file and store them in a dict variable but i got this error.
"TD.txt" looks like this:
o n 38
o m 38
o b 38
n p 9
m y 9
b q 42
y i 14
dict_of_neighbours = {}
with open('TD.txt') as f:
for line in f:
line_data=line.split()
if line_data[0] not in dict_of_neighbours:
_list = list()
_list.append([line_data[1],line_data[2]])
dict_of_neighbours[line_data[0]] = _list
else:
dict_of_neighbours[line_data[0]].append([line_data[1],
line_data[2]])
print(dict_of_neighbours)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
C:\Users\TCHOKO~1.GEO\AppData\Local\Temp/ipykernel_15576/2462892917.py in <module>
8 for line in f:
9 line_data=line.split()
---> 10 if line_data[0] not in dict_of_neighbours:
11 _list = list()
12 _list.append([line_data[1],line_data[2]])
IndexError: list index out of range
what is wrong?
0
-
正式なコメント
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support. -
Hi Geoffrey!
Most likely, there is an empty line in your text file. You would need to catch this edge case to avoid such errors.
Maybe it makes sense to look into some existing parsers, e.g., from the pandas module (Pandas: How to Read and Write Files – Real Python) to generate a DataFrame right away and have a more robust parser with more options and flexibility.
Cheers,
Matthias0
投稿コメントは受け付けていません。
コメント
2件のコメント