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