索引错误超出范围 python

Index error out of range python

出于某种原因,我在尝试 运行 以下代码时遇到此错误

#!/usr/bin/python
import matplotlib.pyplot as plt
x = []
y = []
readFile = open('Out_0_0.txt','r')
sepFile = readFile.read().split('\n')
readFile.close()
for plotPair in sepFile:
    xandy = plotPair.split()
    x.append(int(xandy[0]))
    y.append(int(xandy[1]))
print x
print y

当我删除 x.append 和 y.append 行并仅放置一个打印语句来打印出 xandy 中的内容时,它会打印出数组中的每对值。文本文件有这个

 1 2
 3 4
 5 6
 7 8

我想让它做的就是将第一列存储在 x 数组中,将第二列存储在 y 数组中

问题出在您阅读文件的方式上。

这会起作用。

x = []
y = []
with open('test.txt','r') as data_file:
    for plot_pair in data_file:
        xandy = plot_pair.split()
        x.append(int(xandy[0]))
        y.append(int(xandy[1]))
print(x)
print(y)

在 Notepad++ 等编辑器中打开文件,确保您正在阅读的文件的开头或结尾没有多余的行。

一些快速的...应该工作(未完全测试 :P)

x = []
y = []
with open(inputFile, 'r') as f:
    for line in f:
        nextX, nextY = map(int, line.split(' '))
        x.append(nextX)
        y.append(nextY)

另一个快速想法:确保 txt 文件末尾没有空行。也许还添加一个 if line: 检查。

您可以更有效(更安全)地阅读本文。我所做的第一个更改是在读取文件时使用 with。完成后,这将自动处理关闭文件。

接下来,我删除了 split('\n'),因为它不是必需的。相反,我们将逐行遍历文件并将其拆分为空白。由于这是一个两列文件,我们将用这一行来完成:

fx,fy = line.split()

我把它放在 try/except 中以防文件末尾有空行。这将产生一个 ValueError 并且假设这是文件的结尾。

然后我们将行的列附加到最终数组。

x = []
y = []
with open('test.txt') as f:
    for line in f:
        try:
            fx,fy = line.split()
        except ValueError:  
            break       
        x.append(int(fx))
        y.append(int(fy))

print x
print y

打印出来:

[1, 3, 5, 7]
[2, 4, 6, 8]

最后,我删除了 matplotlib 导入。此示例不需要它。