首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python:如何在循环中只打印一行

Python:如何在循环中只打印一行
EN

Stack Overflow用户
提问于 2021-04-07 15:41:48
回答 3查看 70关注 0票数 1

我只是试图简单地覆盖我的程序中的一个错误,并且我已经使用了try和except函数。下面是我的代码:

代码语言:javascript
运行
复制
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行,所以它打印出来:

代码语言:javascript
运行
复制
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.
Sorry. Try again.

我理解这是因为它在循环中,但这是因为csv文件需要是一个循环,才能打印出正确的结论。有没有办法只打印一行“对不起,当任何输入与csv中的任何内容都不匹配时,请重试。

提前感谢!

EN

回答 3

Stack Overflow用户

发布于 2021-04-07 16:06:41

Svrem的解决方案完全符合您的要求,我在此基础上对其进行了投票--然而,根据经验,在尝试读取csv文件时出现单一的错误消息并不是很有用。您最终可能需要的是一些关于哪些行不好的指导。我的建议大致如下:

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2021-04-07 15:46:57

您可以尝试添加break语句。这将中断循环。

因此在您的情况下,它将是:

代码语言:javascript
运行
复制
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
票数 0
EN

Stack Overflow用户

发布于 2021-04-07 17:22:14

我认为其他答案通过调整你的代码回答了错误的事情。try/except没有做你想让它做的事情。如果您忘记在命令行上提供参数,它将捕获的唯一异常是IndexError,而这并不是您所描述的使用它的目的。

如果只想在没有匹配的行时显示消息,则需要跟踪匹配的行数,例如:

代码语言:javascript
运行
复制
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.")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66981592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档