我只是试图简单地覆盖我的程序中的一个错误,并且我已经使用了try和except函数。下面是我的代码:
import csv
import sys
with open('fake.csv') as csvfile:
sched = csv.reader(csvfile, delimiter=',')
for row in sched:
a = row[1]
try:
if (a == sys.argv[1]):
print(row)
except Exception:
print("Sorry. Try again.")这确实起作用了,但它不是只打印一行,而是根据我的csv文件重新打印,该文件有6行,所以它打印出来:
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.我理解这是因为它在循环中,但这是因为csv文件需要是一个循环,才能打印出正确的结论。有没有办法只打印一行“对不起,当任何输入与csv中的任何内容都不匹配时,请重试。
提前感谢!
发布于 2021-04-07 16:06:41
Svrem的解决方案完全符合您的要求,我在此基础上对其进行了投票--然而,根据经验,在尝试读取csv文件时出现单一的错误消息并不是很有用。您最终可能需要的是一些关于哪些行不好的指导。我的建议大致如下:
import csv
import sys
badLines = []
with open('fake.csv') as csvfile:
sched = csv.reader(csvfile, delimiter=',')
iRows = 1 #iRows is a counter for the current row in the CSV we are on
for row in sched:
a = row[1]
#Below is edited to amend nonsensical code (which is in source) as pointed out by Kemp
if len(sys.argv) > 1:
if (a == sys.argv[1]):
print(row)
else:
badLines.append(iRows)
else:
print("Are you missing a command line argument to this function?")
iRows = iRows + 1
if badLines:
print("bad line entries in CSV found, these are")
print(badLines) #You could of course wrap this into the one print statement, but this is a simple and clear solution, so why bother发布于 2021-04-07 15:46:57
您可以尝试添加break语句。这将中断循环。
因此在您的情况下,它将是:
import csv
import sys
with open('fake.csv') as csvfile:
sched = csv.reader(csvfile, delimiter=',')
for row in sched:
a = row[1]
try:
if (a == sys.argv[1]):
print(row)
except Exception:
print("Sorry. Try again.")
break发布于 2021-04-07 17:22:14
我认为其他答案通过调整你的代码回答了错误的事情。try/except没有做你想让它做的事情。如果您忘记在命令行上提供参数,它将捕获的唯一异常是IndexError,而这并不是您所描述的使用它的目的。
如果只想在没有匹配的行时显示消息,则需要跟踪匹配的行数,例如:
import csv
import sys
count = 0
with open('fake.csv') as csvfile:
sched = csv.reader(csvfile, delimiter=',')
for row in sched:
if (row[1] == sys.argv[1]):
print(row)
count += 1
if count == 0:
print("Sorry, try again.")https://stackoverflow.com/questions/66981592
复制相似问题