查找CSV Fi中不存在的项目

2024-09-29 00:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,它是在csv文件中查找一个项目toFind

with open("file.csv", "r") as file:
        reader = csv.reader(file)
        for item in reader:
            if toFind == item

如果toFind不在csv文件中,如何获得打印“找不到”的代码


Tags: 文件csv项目代码inforifas
3条回答

我会这样实施:

is_found = False
with open("file.csv", "r") as file:
        reader = csv.reader(file)
        for item in reader:
            if toFind == item
                is_found = True
                break # No need to keep on searching so we stop here

if not is_found:
    print "Cannot be Found"

使用一个预设为False的布尔值,我可以确保在循环末尾打印布尔值时,只有在CSV中找到toFind时,它才会包含True

你就快成功了,你只需要检查你的元素的列:

to_find = "item to find"
found = False  # assume the item does not exist
with open("file.csv", "r") as f:
    reader = csv.reader(f)
    for item in reader:
        if to_find in item:  # the item exist, declare it exists and stop reading
            found = True
            break
if not found:
    print("The item `{}` does not exist in the CSV".format(to_find))

更新:根据Jon Clement的建议,对于这种明确的情况,您可能希望使用内置的^{},而不是自己完成整个流程:

to_find = "item to find"
with open("file.csv", "r") as f:
    reader = csv.reader(f)
    if not any(to_find in item for item in reader):
        print("The item `{}` does not exist in the CSV".format(to_find))

这样,您就不必担心在找到匹配项时是否会明显地退出迭代,并且您可以不使用临时变量就可以离开

尝试:

with open("file.csv", "r") as file:
    reader = file.read()
    if toFind not in reader:
        print("Cannot be Found")

相关问题 更多 >