其他选项而不是使用try-except

Hal*_*Hal 8 python file filter try-except

当文本文件中的第2行具有"nope"时,它将忽略该行并继续下一行.是否有另一种方法来写这个没有使用尝试,除了?我可以使用if else语句来执行此操作吗?

文本文件示例:

0 1 
0 2 nope
1 3 
2 5 nope
Run Code Online (Sandbox Code Playgroud)

码:

e = open('e.txt')
alist = []
for line in e:
    start = int(line.split()[0])
    target = int(line.split()[1])
    try:
        if line.split()[2] == 'nope':
            continue
    except IndexError:
        alist.append([start, target])
Run Code Online (Sandbox Code Playgroud)

Kas*_*mvd 6

是的,您可以使用str.endswith()方法来检查线的尾随.

with  open('e.txt') as f:
    for line in f:
        if not line.endswith(('nope', 'nope\n')):
            start, target = line.split()
            alist.append([int(start), int(target)])
Run Code Online (Sandbox Code Playgroud)

请注意,当您使用with语句打开文件时,不需要显式关闭文件,文件将在块结束时自动关闭.

另一种更优化的方法是使用列表推导来拒绝在每次迭代时附加到列表中,并从与常规循环相比的性能中获益.

with open('e.txt') as f:
    alist = [tuple(int(n) for i in line.split()) for line in f if not line.endswith(('nope', 'nope\n'))]
Run Code Online (Sandbox Code Playgroud)

请注意,由于您的代码因为将字符串转换为整数并拆分行等而异常,因此最好使用try-except以防止代码出现可能的异常并正确处理它们.

with  open('e.txt') as f:
    for line in f:
        if not line.endswith(('nope', 'nope\n')):
            try:
                start, target = line.split()
            except ValueError:
                # the line.split() returns more or less than two items
                pass # or do smth else
            try:
                alist.append([int(start), int(target)])
            except ValueError:
                # invalid literal for int() with base 10
                pass # or do smth else
Run Code Online (Sandbox Code Playgroud)

另一种Pythonic方法是使用csv模块来读取文件.在这种情况下,您不需要拆分线和/或使用str.endswith().

import csv
with open("e.txt") as f:
    reader = csv.reader(f, delimiter=' ')
    alist = [(int(i), int(j)) for i, j, *rest in reader if not rest[0]]
    # rest[0] can be either an empty string or the word 'nope' if it's
    # an empty string we want the numbers. 
Run Code Online (Sandbox Code Playgroud)