简体   繁体   English

IndexError:字符串索引超出范围,无法读取文件python中的第一行

[英]IndexError: string index out of range for reading first line in a file python

Hello im writing code that opens a file. 您好,我正在编写打开文件的代码。 it reads the file and does specific tasks if the line currently being read in the file contains content which marks to a task. 如果文件中当前正在读取的行包含标记任务的内容,它将读取文件并执行特定任务。

the first thing I am trying to do, is read the first line and add it to a running score and then move on with the file. 我要做的第一件事是阅读第一行并将其添加到正在运行的乐谱中,然后继续处理文件。 However, i am encountering the error: indexError: string index out of range. 但是,我遇到错误:indexError:字符串索引超出范围。

which I just dont understand I feel like that shouldn't be happening. 我只是不明白,我觉得这不应该发生。

so heres the code that is referenced by the error. 因此,这里是错误所引用的代码。 Followed by the actual error. 其次是实际错误。 Then followed by the full code for context. 然后是用于上下文的完整代码。

    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

The error 错误

   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

The total code 总码

    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 

What the file looks like 该文件是什么样的

50 50

O Ø

30 三十

O Ø

40 40

M 中号

10 20 30 10 20 30

o Ø

5

m

1 2 3 1 2 3

X X

With the code I can see that the file is reading the first line you can see that with the print statement before the code fails. 通过代码,我可以看到文件正在读取第一行,在代码失败之前,可以通过print语句看到文件。

processScores('theText.txt',score)

Grabing intial score from file, inital score set to 50 从文件中获取初始分数,初始分数设置为50

that print statement is running on this line of code 该打印语句在此代码行上运行

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))

So I am to assume that it is moving on to the next part of the code. 因此,我假设它正在继续进行代码的下一部分。 but I am not sure. 但我不确定。

Thank you all very much 非常感谢大家

It looks like line[0] doesn't exist, ie line is empty so you can't read the first character of it. 看起来line[0]不存在,即line为空,因此您无法读取其第一个字符。 Most likely your file is empty or you have a blank line at the end of the file. 您的文件很可能为空,或者文件末尾有空白行。 To debug, you can check each line by doing something like print line or print len(line) . 要进行调试,您可以通过执行诸如print lineprint len(line)类的操作来检查每一行。 You may also want to add some checking to your code to ensure that you don't try and process empty lines, such as if line: or if line.strip(): , which will evaluate to True if there are characters remaining in the line after white space has been stripped from the start and end of the line. 您可能还需要在代码中添加一些检查,以确保您不尝试处理空行,例如if line:if line.strip():如果在代码行中剩余字符,则计算结果为True 。从行的开头和结尾去除空白后的行。

Edit: In your case you'd want something like: 编辑:在您的情况下,您需要类似:

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...

Your line contains empty string after strip() as @figs advice, simply change to this: 您的行在strip()之后包含空字符串,作为@figs建议,只需更改为:

...
if line and line[0].isdigit():
    start = int(line)

And you don't need to repeat strip() twice. 而且您不需要重复两次strip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM