[英]IndexError: string index out of range for reading first line in a file python
您好,我正在编写打开文件的代码。 如果文件中当前正在读取的行包含标记任务的内容,它将读取文件并执行特定任务。
我要做的第一件事是阅读第一行并将其添加到正在运行的乐谱中,然后继续处理文件。 但是,我遇到错误:indexError:字符串索引超出范围。
我只是不明白,我觉得这不应该发生。
因此,这里是错误所引用的代码。 其次是实际错误。 然后是用于上下文的完整代码。
def processScores( file, score):
#opens file using with method, reads each line with a for loop. If content in line
#agrees with parameters in if statements, executes code in if statment. Otherwise, ignores line
with open(file,'r') as f:
for line in f: #starts for loop for all if statements
line = line.strip()
if line[0].isdigit():
start = int(line.strip())
score.initialScore(start) #checks if first line is a number if it is adds it to intial score
错误
processScores('theText.txt',score)
Grabing intial score from file, inital score set to 50
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
processScores('theText.txt',score)
File "C:/Users/christopher/Desktop/hw2.py", line 49, in processScores
if line[0].isdigit():
IndexError: string index out of range
总码
class Score:
# class to hold a running score, from object to parameter
# also to set number of scores that contribute to total of 1
def __init__(self):
#initalizes the running score and score input accumilators
self.runScore = 0
self.scoreInputs = 0
def initialScore(self, start):
#takes the initial score in line one of the file and updates
#the running score to the inital score
self.runScore += start
print('Grabing intial score from file, inital score set to ' + str(start))
def updateOne (self, amount):
#updates running score by amount and Score input by 1
self.runScore += amount
self.scoreInputs += 1
print('Adding ' + str(amount) + ' to score, number of scores increased by 1. Current number of points scored ' + str(self.runScore) + ', current number of scores at ' + str(self.scoreInputs))
def updateMany(self,lst):
#updates running score by the sum of the list and score inputs by the amount of
# number of items in the list
self.runScore += sum(lst)
self.scoreInputs += len(lst)
print('Adding the sum of ' + str(len(lst)) + 'scores to score. Score increased by ' + str(sum(lst)) + '. current number of points scored ' + str(self.runScore) + ', current number of scores at ' + str(self.scoreInputs))
def get(self):
#returns the current score based on total amount scored
print('Grabbing current score')
print(self.runScore)
def average(self):
#returns the average of the scores that have contributed to the total socre
print('calculating average score')
print(self.runScore // self.scoreInputs)
score = Score() # initize connection
def processScores( file, score):
#opens file using with method, reads each line with a for loop. If content in line
#agrees with parameters in if statements, executes code in if statment. Otherwise, ignores line
with open(file,'r') as f:
for line in f: #starts for loop for all if statements
line = line.strip()
if line[0].isdigit():
start = int(line.strip())
score.initialScore(start) #checks if first line is a number if it is adds it to intial score
elif line == 'o' or line == 'O':
amount = int(next(f))
score.updateOne(amount) #if line contains single score marker, Takes content in next line and
#inserts it into updateOne
elif line == 'm'or line == 'M':
scoreList = next(f)
lst = []
for item in scoreList:
lst.append(item)
score.updateMany(lst) # if line contains list score marker, creates scoreList variable and places the next line into that variable
# creates lst variable and sets it to an empty list
# goes through the next line with the for loop and appends each item in the next line to the empty list
# then inserts newly populated lst into updateMany
elif line == 'X':
score.get(self)
score.average(self) # if line contains terminator marker. prints total score and the average of the scores.
# because the file was opened with the 'with' method. the file closes after
该文件是什么样的
50
Ø
三十
Ø
40
中号
10 20 30
Ø
五
米
1 2 3
X
通过代码,我可以看到文件正在读取第一行,在代码失败之前,可以通过print语句看到文件。
processScores('theText.txt',score)
从文件中获取初始分数,初始分数设置为50
该打印语句在此代码行上运行
def initialScore(self, start):
#takes the initial score in line one of the file and updates
#the running score to the inital score
self.runScore += start
print('Grabing intial score from file, inital score set to ' + str(start))
因此,我假设它正在继续进行代码的下一部分。 但我不确定。
非常感谢大家
看起来line[0]
不存在,即line为空,因此您无法读取其第一个字符。 您的文件很可能为空,或者文件末尾有空白行。 要进行调试,您可以通过执行诸如print line
或print len(line)
类的操作来检查每一行。 您可能还需要在代码中添加一些检查,以确保您不尝试处理空行,例如if line:
或if line.strip():
如果在代码行中剩余字符,则计算结果为True
。从行的开头和结尾去除空白后的行。
编辑:在您的情况下,您需要类似:
with open(file,'r') as f:
for line in f:
# strip white space
line = line.strip()
# if line is not empty
if line:
if line[0].isdigit():
# do this
elif line == 'o'
# do that
# etc...
您的行在strip()之后包含空字符串,作为@figs建议,只需更改为:
...
if line and line[0].isdigit():
start = int(line)
而且您不需要重复两次strip() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.