简体   繁体   中英

Using input to filter parsed csv through Dictreader

I am new to python and my objective is to create a basic script capable of filtering a csv database through user input. I searched through various posts and answers and came up with this code that doesn't give the desired responses for some reason, can somebody tell me if it is correct or an erroneous approach? Thank you very much for your help and here is the code below:

import csv

from encodings import utf_8
from csv import DictReader
from multiprocessing import Value
from typing import Dict
with open('Book.csv', newline='', ) as file :
    reader= DictReader(file)
  
    for row in reader :
     print(row)
    
  

    ask_age=(input("enterage:"))
    
    for row in reader :
     for key,val in row.items : 
        if ask_age==str in row.items['Age',str] is True : 
         print(row.items['Name',str])

Here is a sample of the database (it's a mock database as I am still figuring out the script)

Age,Name,Sex
10,brian,male
30,amilia,female
40,raylie,female 

Prompt:

Enter age: 10

Output:

brian is 10

Script:

import csv

ask_age = (input("Enter age:"))

with open('Book.csv', 'r') as file :
    reader = csv.reader(file)
  
    for row in reader :
        if row[0] == ask_age:
            print(row[1] + ' is ' + ask_age) 

CSV format:

|----|--------|--------|
| 10 | brian  | male   |
| 30 | amilia | female |
| 40 | raylie | female |

Here's a short example making use of DictReader

from csv import DictReader

ask_age = input("enter age: ")

with open('Book.csv') as csv_file :
    reader = DictReader(csv_file)
    for row in reader:
        if row.get('Age') == ask_age:
            print(f"{row.['Name']} is {row['Age']} ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM