查找CSV文件中不存在的项目

时间:2018-04-02 13:36:29

标签: python csv

我有以下代码,它是在csv文件中找到一个项目$details

toFind

如果csv文件中没有with open("file.csv", "r") as file: reader = csv.reader(file) for item in reader: if toFind == item ,我如何才能获得打印“无法找到”的代码?

3 个答案:

答案 0 :(得分:2)

尝试:

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

答案 1 :(得分:2)

你几乎得到它,你只需要检查元素的列:

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的建议,对于诸如此类的明确案例,您可能希望使用内置any()而不是执行整个过程流动自己:

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))

这样,如果找到匹配项,您就不必担心明确退出迭代,并且可以在没有临时变量的情况下离开。

答案 2 :(得分:1)

我会这样实现:

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。