在迭代线python时正确使用异常

时间:2015-01-19 01:33:22

标签: python file exception exception-handling

尝试编写代码,在调用方法之后,代码将遍历行,直到找到只包含数字的行。然后它会将该数字添加到一个数量。这就是我在思考的问题,我无法完全理解这一点。

 elif line == 'o' or line == 'O':
 amount = next(f)
            try:
                next(f)
            except TypeError:
                next(f)
            print(line)#DEBUG TEST****
            score.updateOne(amount)

所以,如果一行包含字母o,那么它是否会转到下一行并将其添加到金额中。但如果金额是空格或字符串。我需要它来尝试添加下一行。如果那不起作用,请尝试下一个,直到找到数字并将其添加到该行。

在线研究让我走到这一步,但其他人可以填补空白吗?

谢谢

为了更好地理解,这里是代码试图读取的文件:

50

0

30

0

40

中号

10 20 30

0

5

1 2 3

X

这是函数中使用类方法执行任务的代码。我没有发布课程及其方法导致没有意义

score = Score() # initize connection       

def processScores(文件,分数):

使用with方法打开文件,用for循环读取每一行。如果内容符合

与elif语句中的参数一致,在if语句中执行代码。否则,忽略行

with open(file,'r') as f:
    for line in f:  #starts for loop for all if statements
        line = line.strip()
        if line.isdigit():
            start = int(line)
            score.initialScore(start)
            print(line)#DEBUG TEST**** #checks if first line is a number if it is adds it to intial score

        elif len(line) == 0:
            print(line)#DEBUG TEST****
            continue        #if a line has nothing in it. skip it  

        elif line == 'o' or line == 'O':
            try:
                amount = int(line)
            except ValueError:
                continue
            else:
                score.updateOne(amount)
            amount =  next(f)
            print(line)#DEBUG TEST****
            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);next(f)
            lst = []
            for item in scoreList:
                print(line)#DEBUG TEST****
                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':
            print(line)#DEBUG TEST****
            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 

2 个答案:

答案 0 :(得分:0)

而不是写作:

try:
    next(f)
except ValueError:
    next(f)

您希望在try块中进行类型转换。例如:

for line in f:
    try:
        # try to convert the line to a number
        value = float(line)
    except ValueError:
        # oops! It wasn't a number... continue on with the next line.
        continue
    else:
        # good! It was a number, update the score.
        score.updateOne(value)

你的原始代码使用了next来推进迭代器,但通常这是不必要的麻烦。例如,如果您阅读文件末尾,则next来电将会抛出StopIteration,而您却无法处理代码中的内容。更好的方法是利用f可以迭代的事实(即,假设f是一个开放的,类似文件的对象),所以写for line in f:就是全部你需要循环遍历文件的行。

现在,您的文件有一个特殊的结构,oO表示您想要阅读的传入值。以下是一些代码:

total = 0
with open("data.txt") as f:
    for header in f:
        if header.strip().lower() == "o":
            for line in f:
                try:
                    value = int(line)
                except ValueError:
                    continue
                else:
                    total += value
                    break
            else:
                raise RuntimeError("No value found!")

如果您的文件格式错误,则会抛出RuntimeError,这意味着它的o后面没有值。

答案 1 :(得分:0)

我希望您尝试读取文件,如果是,那么代码应该类似于

score = 0
with open('mydata.txt') as fp:
  for line in iter(fp.readline, ''):
     try:
         score += int(line)
     except ValueError as e:
         print "something is wrong with value "+e.message

print score