简体   繁体   English

如何继续尝试/除外

[英]How to continue a try/except

I'm currently learning about "try" and "except" concepts and I have a small question.我目前正在学习“尝试”和“除外”概念,我有一个小问题。

def sum_file():
    try:
        with open("text.txt") as entry:
            result = 0
            try:
                for line in entry:
                    result += int(line.strip())
                    print(result)
            except ValueError:
                print("Non-integer number entered")
    except:
        print("Non-existent file.")

Each line of the file is a number, some numbers are integers and others are floats.文件的每一行都是一个数字,一些数字是整数,其他数字是浮点数。 The code correctly sums the first integers but when the first float appears the program stops, when there are more lines further.代码正确地对第一个整数求和,但是当第一个浮点数出现时,程序停止,当还有更多行时。 How do I modify the code for it to continue the operation?如何修改代码使其继续操作?

You need to put the second try block inside your loop:您需要将第二个try块放入循环中:

def sum_file():

    try:
        with open("text.txt") as entry:
            result = 0
            for line in entry:
                try:
                    result += int(line.strip())
                    print(result)
                except ValueError:
                    print("Non-integer number entered")
    except:
        print("Non-existent file.")

or you can use re to help you.或者你可以使用re来帮助你。

re.match(r".*\\D+.*", line) match any line which contains one or more not [0-9] character re.match(r".*\\D+.*", line)匹配任何包含一个或多个[0-9] 字符的行

from io import StringIO
import re

text_txt = """\
3.1
123
4 b 5 6
     7.2   
c'] ? 9
  10
"""


def sum_file():
    with StringIO(text_txt) as f:
        result_list = []
        for line in [_.strip() for _ in f]:
            m = re.match(r".*\D+.*", line)
            print("Non-integer number entered") if m else (print(line), result_list.append(int(line)))
        print(f'result: {sum(result_list)}') if result_list else None

sum_file()

output输出

Non-integer number entered
123
Non-integer number entered
Non-integer number entered
Non-integer number entered
10
result: 133

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

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