Python 如何通过csv文件搜索单词?

Python 如何通过csv文件搜索单词?,python,csv,Python,Csv,这可能是一个非常简单的问题,但我是python新手,我搜索过网络,但我无法解决这个问题。我有一个csv文件,我需要在第一行的列中搜索特定的单词。我该怎么做 我使用python的默认csv模块逐行读取csv文件。由于您指定我们必须只在第一行中搜索,因此我在搜索csv的第一行后使用break停止执行。您可以删除中断,以便在整个csv中进行搜索。希望这能奏效 import csv a='abc' #String that you want to search with open("testin

这可能是一个非常简单的问题,但我是python新手,我搜索过网络,但我无法解决这个问题。我有一个csv文件,我需要在第一行的列中搜索特定的单词。我该怎么做

我使用python的默认csv模块逐行读取csv文件。由于您指定我们必须只在第一行中搜索,因此我在搜索csv的第一行后使用break停止执行。您可以删除中断,以便在整个csv中进行搜索。希望这能奏效

import csv
a='abc'     #String that you want to search
with open("testing.csv") as f_obj:
    reader = csv.reader(f_obj, delimiter=',')
    for line in reader:      #Iterates through the rows of your csv
        print(line)          #line here refers to a row in the csv
        if a in line:      #If the string you want to search is in the row
            print("String found in first row of csv")
        break
您必须添加“str(line)”以将行转换为字符串,然后进行比较。

可能的重复项
import csv
a='abc'     #String that you want to search
with open("testing.csv") as f_obj:
    reader = csv.reader(f_obj, delimiter=',')
    for line in reader:      #Iterates through the rows of your csv
        print(line)          #line here refers to a row in the csv
        if a in str(line):      #If the string you want to search is in the row
            print("String found in first row of csv")
        break