Python"字符串索引超出范围"尝试从外部文件读取字符串数据时

时间:2016-05-18 15:23:48

标签: python indexing traceback

我收到以下错误

Traceback (most recent call last):
    File "script.py", line 16, in <module>
        if char[x] == " ":
IndexError: string index out of range

这些代码行

for file in files:
    f = open(file, "r")
    file_num += 1
    for line in file:
       for char in line:
           if char[x] == " ":
              break
           else:
              x += 1

我试图让它逐行读取文件并选出空格之间的区域,以便在脚本的其他地方存储为字符串变量。我几乎都是一个菜鸟,所以任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:2)

char将始终是长度为1的字符串。 在某些char不是' '之后,x将是一些大于0的值(我假设这是x初始化的值) 。然后你得到了IndexError

您的代码可以大大简化为:

for file in files:
    f = open(file, "r")
    file_num += 1
    for line in file:
       for char in line:
           if char == ' ':
              break

答案 1 :(得分:0)

file_num = len(files)
for file in files:
  with open(file, 'r') as f: # with closes the file for you
    words = line.split() # split the line by white space into a list