【问题标题】:Search specific column for string input in a csv file [duplicate]在 csv 文件中搜索字符串输入的特定列[重复]
【发布时间】:2021-02-27 21:36:27
【问题描述】:

我正在尝试创建一个程序,在其中接受用户输入并查看它是否位于 CSV 文件的特定列(第 10 列)中,然后打印出找到输入的整行。我主要在将字符串与列中的任何值匹配的代码上遇到问题。

city = input("Enter a city name: " ).upper()
with open('file.csv','rt') as file:
        reader = csv.reader(file, delimiter=' ' )
        for row in reader:
                if city == row[9]:
                        print(row)
                else:
                        print(input("City not in file. Enter a city name: "))
                        break

CSV 文件如下所示:

ID,Date,Age,Sex,Race,City...
1,06/08/2004,32,F,White,Denver
2,06/23/2004,23,M,Black,Hartford
.
.
.

我缩短了它,所以我没有列出所有内容,但 CSV 中的城市列将是第 10 列,而不是上面的第 6 列。

【问题讨论】:

  • 您能否提供一个 CSV 文件的示例?
  • @user3431635 我已将其添加到帖子中,谢谢。
  • 你没有说你的代码到底出了什么问题......除了每次迭代都运行 else 之外,你的代码很好

标签: python python-3.x csv


【解决方案1】:

如果没有匹配项,您将在第一行之后退出 for 循环。只有在找到匹配项后才尝试跳出 for 循环。如果未找到匹配项,则会打印一条消息。

import csv

CITY_NAME_COL = 5

prompt = "Enter a city name: "
found_city = False

with open('cities.csv','rt') as file:
        reader = csv.reader(file)
        next(reader, None)
        city_name = input(prompt)
        while not found_city:
            for row in reader:
                if city_name == row[CITY_NAME_COL]:
                    found_city = True
                    print(row)
                    break
            else:
                    city_name = input(f"City not in file. {prompt}")
                    file.seek(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2016-06-01
    相关资源
    最近更新 更多