简体   繁体   中英

how to show specific columns from a list, tabulate and print them on the console

i am currently trying to do some password manager and i am stuck on how to elegantly print specific colums from a list. I could do this in a very dirty way but im sure there has to be a one-line way of managing it. The csv_file has 3 colums: "service", "account" and "password". I want to show only the firtst two colums that satisfies the user input in a tabulated way, to imitate a table. Thank you in advanced for your time: ). This is how I tried to do it:

        reader = csv.DictReader(csv_file)
        service = input("PLEASE SPECIFY THE SERVICE \n ")
        header=[["service","account"]]
        for line in reader:
            if line["service"] != service:
                reader.remove(line)
        print(tabulate(([header, [el["service"], el["account"]] for el in reader]))

How about this?

reader = csv.DictReader(csv_file)
service = input("PLEASE SPECIFY THE SERVICE \n ")
print(tabulate(line for line in reader if line["service"] == service,
               header=["service","account"])

After a long investigation i found a way of doing it:

service = input("PLEASE SPECIFY THE SERVICE \n")
reader = csv.DictReader(csv_file)
header=["service","account"]
valid=[]
for line in reader:
    if line["service"] != service:
        valid.append([line["service"], line["account"], line["password"]])
print(tabulate([header, *[[line[0], line[1]] for line in valid]]))

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