我想在CSV文件中搜索一个值并打印整行
CSV文件如下所示:
some : 111
name : 222
test : 333
我使用这个代码:
import csv
with open(fin , 'r') as csvfile :
reader = csv.reader(csvfile)
for line in reader:
if '222' in line:
print(line)
问题是它只打印整行,如果我搜索name: 222
但是如果我只搜索222
,它什么也没有显示。
我在搜索222的时候就在期待它了。打印name: 222
3条答案
按热度按时间4xy9mtcn1#
其他答案已经提供了解决方案,但让我们看看为什么你的解决方案不起作用。
Csv代表“逗号分隔值”,因此csv读取器希望每行都用逗号分隔(如果指定,也可以使用其他分隔符)。由于您使用的是
csv.reader()
,因此对于每一行,它都会返回一个以逗号分隔的列表。例如,第二行返回为["name : 222"]
。当然,"222"
不在这个列表中,但"name : 222"
在。hrysbysz2#
您可以使用此代码搜索行中任何元素的子字符串值。
您将以列表
['name : 222']
中的一行形式获得结果j7dteeu83#
这不是一个CSV文件,所以不要使用
csv
模块来读取它。分隔符是字符串' : '
,因此将文件作为行读取并调用split()
。