在遍历行 python 时正确使用异常
properly using exceptions while interating through lines python
尝试编写代码,在调用方法后,代码将遍历行,直到找到其中只有一个数字的行。然后它将把这个数字加到一个数量上。这就是我在想的我无法完全理解这个问题。
elif line == 'o' or line == 'O':
amount = next(f)
try:
next(f)
except TypeError:
next(f)
print(line)#DEBUG TEST****
score.updateOne(amount)
所以要尝试做的是,如果一行包含字母 o,那么它将转到下一行并将其添加到一个数量。但如果金额为空 space 或字符串。我需要它来尝试添加下一行。如果这不起作用,请尝试下一个,直到找到数字并将其添加到行中。
在线研究让我走到了这一步,但还有其他人可以填补空白吗?
谢谢
为了更好地理解,这里是代码试图读取的文件:
50
O
30
O
40
男
10 20 30
o
5
米
1 2 3
X
这里是函数中使用 class 方法执行任务的代码。我没有发布 class 及其方法,因为没有意义
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
而不是写作:
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:
就可以了您需要循环遍历文件的行。
现在,您的文件有一个特殊的结构,其中 o
或 O
表示您想要读取的传入值。下面是一些代码:
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
后面没有值。
我希望你正在尝试读取文件,如果是,那么代码应该类似于
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
尝试编写代码,在调用方法后,代码将遍历行,直到找到其中只有一个数字的行。然后它将把这个数字加到一个数量上。这就是我在想的我无法完全理解这个问题。
elif line == 'o' or line == 'O':
amount = next(f)
try:
next(f)
except TypeError:
next(f)
print(line)#DEBUG TEST****
score.updateOne(amount)
所以要尝试做的是,如果一行包含字母 o,那么它将转到下一行并将其添加到一个数量。但如果金额为空 space 或字符串。我需要它来尝试添加下一行。如果这不起作用,请尝试下一个,直到找到数字并将其添加到行中。
在线研究让我走到了这一步,但还有其他人可以填补空白吗?
谢谢
为了更好地理解,这里是代码试图读取的文件:
50
O
30
O
40
男
10 20 30
o
5
米
1 2 3
X
这里是函数中使用 class 方法执行任务的代码。我没有发布 class 及其方法,因为没有意义
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
而不是写作:
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:
就可以了您需要循环遍历文件的行。
现在,您的文件有一个特殊的结构,其中 o
或 O
表示您想要读取的传入值。下面是一些代码:
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
后面没有值。
我希望你正在尝试读取文件,如果是,那么代码应该类似于
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