当文本文件中的第 2 行有 'nope' 时,它将忽略该行并继续下一行。有没有不使用 try 和 except 的另一种写法?我可以使用 if else 语句来执行此操作吗?
文本文件示例:
0 1
0 2 nope
1 3
2 5 nope
代码:
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])
最佳答案
是的,您可以使用 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)])
请注意,当您使用 with
语句打开文件时,您无需显式关闭文件,该文件将在 block 末尾自动关闭。
解决此问题的另一种更优化的方法是使用列表理解,以拒绝在每次迭代时附加到列表,并从其与常规循环相比的性能中受益。
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'))]
请注意,由于将字符串转换为整数并拆分行等,您的代码容易出现异常。最好使用 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
另一种 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.
关于python - 其他选项而不是使用 try-except,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50432668/