[英]How to filter-out and print only rows that have field with a specific value using csv.DictReader?
我正在阅读 Python 中的 CSV 文件。
with open('file.csv', newline='') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['id'], row['first_name'], row['last_name'], row['state'])
如何添加一些代码来过滤并仅打印特定“状态”的行? 我的意思是程序会询问用户他们想要打印哪个 state,并且只打印用户想要的特定 state 的行(还包括“id”、“first_name”、“last_name”)。
我不能使用 Pandas 或 Numpy 库。
这是使用列表推导的建议。 请注意,我们首先在这里加载所有记录,然后进行过滤。 其他解决方案建议在加载文件时进行过滤。
import csv
def filter_by_state(rows, target_state):
return [row for row in rows if row['state'] == target_state]
with open('file.csv') as f:
# This loads all records into memory and closes the CSV file afterwards
rows = list(csv.DictReader(f))
rows = filter_by_state(rows, 'OK')
if row['state'] == something:
print(row['id'], row['first_name'], row['last_name'], row['state'])
应该可以,如果您希望用户选择,让他将变量“某物”修改为他想要的
使用方法input()
您要求用户输入(所需的状态)。 使用if
语句,您可以控制打印的 output。
with open('file.csv', newline='') as f:
reader = csv.DictReader(f)
user_state = input('Enter the searched state')
for row in reader:
if user_state == row['state']:
print(row['id'], row['first_name'], row['last_name'], row['state'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.