首页 > 解决方案 > Python:如何在循环中只打印一行

问题描述

我只是想简单地覆盖我的程序中的一个错误,我已经使用了 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.")

这确实有效,但不是只打印一行,而是根据我有 6 行的 csv 文件重新打印,所以它打印出来:

Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.

我知道这是因为它来自循环内,但这是由于 csv 文件需要成为一个循环才能打印出正确的结论。有什么方法可以只打印一行说“对不起,当任何输入与 csv 中的任何内容都不匹配时再试一次。

提前致谢!

标签: python

解决方案


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

推荐阅读