导入文本文件 - 列表索引超出范围

时间:2016-05-04 10:09:38

标签: python

infile = open("/Users/name/Downloads/points.txt", "r")
line = infile.readline()
while line != "":
    line = infile.readline()
    wordlist = line.split()
    x_co = float(wordlist[0])
    y_co = float(wordlist[1])

我环顾四周,但实际上找不到对我的问题有用的东西。

我有一个带有x(第一列)和y(第二列)坐标的.txt文件(见图片)。 我希望每个x和y坐标分开,但是当我运行我的代码时,我总是得到一个错误:

x_co = float(wordList[0])
IndexError: list index out of range

感谢您的帮助!

Textfile with the coordinates

2 个答案:

答案 0 :(得分:1)

filename = "/Users/name/Downloads/points.txt"
with open(filename) as infile:
    for line in infile:
        wordlist = line.split()
        x_co = float(wordlist[0])
        y_co = float(wordlist[1])

with自动处理文件关闭

对于Python中更多这样的惯用方法,read this

答案 1 :(得分:0)

最好你可以这样做:

infile = open("/Users/name/Downloads/points.txt", "r")
for line in infile:
    if line:
        wordlist = line.split()
        x_co = float(wordlist[0])
        y_co = float(wordlist[1])