python - 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 中的任何内容都不匹配时再试一次。
提前致谢!
解决方案
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
推荐阅读
- android - BLE readCharacteristic(characteristic) 返回 false (Accu Check Instant Gluco Meter)
- django - 使用聚合将原始 SQL 查询集成到 Django ORM 中
- angular - 垫日历的最大日期
- node.js - 为什么每个 npm ip 包都给我 127.0.0.1 而不是 192.168.xx.xx?
- swift - 矩形进度条swiftUI
- python - 使用 Pandas 读取具有列组的数据
- java - 使用 maven 构建的 Docker 映像看不到静态文件
- reactjs - 如何将 Google Classroom API 与 react-native 集成?
- reactjs - 数据库和 CRUD 之间有什么关系?
- html - 始终使用 jquery 在动态折叠中显示前两行