csv 在列表中搜索一个值并返回整行

yfjy0ee7  于 2023-05-04  发布在  其他
关注(0)|答案(3)|浏览(130)

我想在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

4xy9mtcn

4xy9mtcn1#

其他答案已经提供了解决方案,但让我们看看为什么你的解决方案不起作用。
Csv代表“逗号分隔值”,因此csv读取器希望每行都用逗号分隔(如果指定,也可以使用其他分隔符)。由于您使用的是csv.reader(),因此对于每一行,它都会返回一个以逗号分隔的列表。例如,第二行返回为["name : 222"]。当然,"222"不在这个列表中,但"name : 222"在。

hrysbysz

hrysbysz2#

您可以使用此代码搜索行中任何元素的子字符串值。

import csv

# Define the value to search
search_value = '222'

with open('file.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)

    for line in reader:
        # Check if the search value is a substring of any element in the line
        if any(search_value in element for element in line):
            # Print the entire line
            print(line)

您将以列表['name : 222']中的一行形式获得结果

j7dteeu8

j7dteeu83#

这不是一个CSV文件,所以不要使用csv模块来读取它。分隔符是字符串' : ',因此将文件作为行读取并调用split()

with open(fin , 'r') as csvfile:
    for line in csvfile:
        row = line.strip().split(' : ')
        if '222' in row:
            print(row)

相关问题