【发布时间】:2018-02-25 07:39:49
【问题描述】:
这可能是一个非常简单的问题,但我是 python 新手,我已经搜索了网络但是我无法解决问题。我有一个 csv 文件,我需要在其第一行的列中搜索特定的单词。我怎样才能做到这一点?
【问题讨论】:
这可能是一个非常简单的问题,但我是 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
【讨论】:
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
您必须添加“str(line)”才能将行转换为字符串,然后进行比较。
【讨论】: