CSV Row Filter
Filter CSV rows by column value conditions.
Frequently Asked Questions
Code Implementation
import csv
import io
def filter_csv(csv_text: str, column: str, condition: str, value: str) -> str:
"""
Filter CSV rows by condition on a column.
condition: 'contains' | 'equals' | 'gt' | 'lt' | 'not_contains'
"""
reader = csv.DictReader(io.StringIO(csv_text))
if reader.fieldnames is None:
return ""
rows = []
for row in reader:
cell = row.get(column, "")
if condition == "contains" and value.lower() in cell.lower():
rows.append(row)
elif condition == "equals" and cell == value:
rows.append(row)
elif condition == "not_contains" and value.lower() not in cell.lower():
rows.append(row)
elif condition in ("gt", "lt"):
try:
if condition == "gt" and float(cell) > float(value):
rows.append(row)
elif condition == "lt" and float(cell) < float(value):
rows.append(row)
except ValueError:
pass
out = io.StringIO()
writer = csv.DictWriter(out, fieldnames=reader.fieldnames)
writer.writeheader()
writer.writerows(rows)
return out.getvalue()
csv_data = """name,age,city
Alice,30,New York
Bob,25,London
Carol,35,New York"""
print(filter_csv(csv_data, "city", "equals", "New York"))
print(filter_csv(csv_data, "age", "gt", "28"))
Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.