如何打印CSV文件中包含指定关键词的行?解决现有代码仅支持精确匹配的问题
Got it, let's fix this so your code finds rows that contain the keyword instead of requiring an exact match. Here's what's going wrong and how to adjust it:
Your original code uses ==, which enforces a strict exact match—only when the input keyword is identical to the cell content will it trigger a print. To switch to "contains" logic, we'll use Python's in operator, which checks if a string exists as a substring within another.
Solution 1: Check only the first two columns (matches your original logic)
We'll replace the separate == checks with in and combine them into a single or condition:
import csv import sys # Input the keyword to search for name = input('Enter name to find\n') # Read the CSV file csv_file = csv.reader(open('test.csv', "r"), delimiter=",") # Loop through each row for row in csv_file: # Check if the keyword is present in either the first or second column if name in row[0] or name in row[1]: print(row)
Solution 2: Check all columns in the row (more flexible)
If you want to search every cell in a row instead of just the first two, use the any() function to iterate through all cells in the row:
import csv import sys name = input('Enter name to find\n') csv_file = csv.reader(open('test.csv', "r"), delimiter=",") for row in csv_file: # Check if the keyword exists in any cell of the current row if any(name in cell for cell in row): print(row)
Bonus: Case-insensitive search
To make the search ignore uppercase/lowercase differences (e.g., input "john" matches "John" or "JOHN"), convert both the input and cell content to lowercase before checking:
import csv import sys # Convert input to lowercase for case-insensitive matching name = input('Enter name to find\n').lower() csv_file = csv.reader(open('test.csv', "r"), delimiter=",") for row in csv_file: # Check each cell (converted to lowercase) for the keyword if any(name in cell.lower() for cell in row): print(row)
With these changes, your code will now print any CSV row that includes your specified keyword, rather than only exact matches!
内容的提问来源于stack exchange,提问作者DDD

