Home > Net >  Python How to retrieve a specific cell value from a csv file based on other cell values in the same
Python How to retrieve a specific cell value from a csv file based on other cell values in the same

Time:02-17

Currently, I have a code whereby "users" will key in their username and password to log in.

uname = input("Enter uname: ")
pword = input("Enter pword: ")
.
.
.
if row[1] == pword and row[0] == uname:
    LOGIN()

However, I wish to add an "update info" and "generate report" function.

How can I code, using python, such that I can retrieve the "e unit price" of a specific row of the CSV file? (e.g. uname = donnavan12 and pword = Onwdsna)?

enter image description here

Another question that I have is: How can I code, using python, such that I can retrieve the sum of a particular column (e.g. "energy saved") with (e.g. uname = donnavan12 and pword = Onwdsna)?

enter image description here

Sorry that I don't have codes of what I have tried because I don't even know where to begin. I only learned basic python in the past and used dataframe which was much easier but in this project, Pandas is not allowed so I'm rather stumped. (I also added minimal code as I'm afraid of getting my groupmates striked for plagiarism. Please let me know if more code is necessary.)

CodePudding user response:

Try using DictReader in the csv module

Example code:

mcsv = csv.DictReader(filename)

rows = list(mcsv)


def get_value(myname, mypass):
    for row in rows:
        if row['uname']==myname and row['pass'] == mypass:
            return row['value']


def get_sum(myname, mypass, clm):
    esaved = 0
    for row in rows:
        if row['uname']==myname and row['pass'] == mypass:
            esaved  = int(row[clm])
    return esaved

print(get_value('abc', '123'))
print(get_sum('abc', '123', 'energy saved'))

Input

uname pass e unit price energy saved
abc 123 100 10
cde 456 101 11
abc 123 100 13
fgh 789 102 12

Output

e unit price:  100
energy saved:  23
  • Related