You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取CSV文件查询不存在值时程序终止如何修复

问题根因

你之前添加else不生效,是因为else和遍历每行的if/elif分支绑定,只会在单条数据不匹配时触发,而非遍历完所有数据都无匹配时才触发,所以达不到预期效果。另外你贴出的代码里def booking_court()行末尾缺失了必填的冒号,也会导致语法错误。

修复后代码
import csv
# 确保你已经正确初始化console,例如from rich.console import Console; console = Console()

def booking_court():
    location = console.input("[bold bright_yellow]Please Enter the Name of the Chosen Gym:[/] ").lower().title()
    # 新增匹配标记位
    found = False
    # 补充encoding避免中文乱码,可根据你的文件编码调整
    with open("location2.csv", encoding="utf-8") as csvfile:
        csvreader = csv.reader(csvfile, delimiter=',')
        for idx, row in enumerate(csvreader):
            if idx == 0:
                titles = row
                continue
            if location in row[0]:
                # 匹配到数据后修改标记位
                found = True
                for key, value in zip(titles, row):
                    console.print("[bold yellow]%s: [/][bold blue]%s[/]" % (key, value))
                console.print("**********************************************************************")
    # 所有行遍历完成后统一判断匹配状态
    if not found:
        console.print("[bold red]未查询到对应名称的健身房,请确认输入后重试[/]")
关键修改点
  • 新增found标记变量,初始状态为未找到
  • 匹配到目标数据时将标记改为已找到状态
  • 所有数据遍历完成后再判断标记状态,未找到时统一输出提示,不会直接终止程序
  • 补充了文件读取的encoding参数,避免中文乱码问题
  • 调整了首行表头判断的逻辑,用continue减少嵌套层级

如果需要实现输入错误后自动重新请求输入,把输入和查询逻辑套入while True循环即可,用户输入指定退出关键词(比如q)时调用break终止循环即可。

内容的提问来源于stack exchange,提问作者Olivia Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:09:04