簡體   English   中英

IndexError:字符串索引超出范圍,無法讀取文件python中的第一行

[英]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 lineprint 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM