【发布时间】:2015-01-19 01:33:21
【问题描述】:
尝试编写代码,在调用方法后代码将遍历行,直到找到其中只有一个数字的行。然后它将将该数字添加到一个金额中。这就是我正在考虑的问题,我无法完全解决这个问题。
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
哦
30
哦
40
M
10 20 30
o
5
米
1 2 3
X
这是函数中使用类方法执行任务的代码。我没有发布课程及其方法,因为没有意义
score = Score() # initize connection
def processScores(file, score):
使用 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
【问题讨论】:
标签: python file exception exception-handling