I have the code:
def checkdetails(username, password):
with open('Data.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
print(row)
if username == row[0]:
#This is where i will need to check if the password in the next column matches
This searches through the csv's first column in order to see if the username exists. It works.
What i need it to do next is move along to the next column in that row and if it matches the value
Just do:
if row[0] == username and row[1] == password:
Related
I'm new to Python so excuse me if my question is kind of dumb.
I send some data into a csv file (I'm making a password manager). So I send this to this file (in this order), the name of the site, the e-mail corresponding and finally the password.
But I would like to print all the names already written in the csv file but here is my problem, for the first row it does print the whole row but for the following rows it works just well.
Here is my code, I hope u can help me with this.
csv_file = csv.reader(open('mycsvfile.csv', 'r'), delimiter=';')
try :
print("Here are all the sites you saved :")
for row in csv_file :
print(row[0])
except :
print("Nothing already saved")
Maybe it can help, but here is how I wrote my data into the csv file:
#I encrypt the email and the password thanks to fernet and an already written key
#I also make sure that the email is valid
file = open('key.key', 'rb')
key = file.read()
file.close()
f = Fernet(key)
website = input("web site name : \n")
restart = True
while restart :
mail = input("Mail:\n")
a = isvalidEmail(mail)
if a == True :
print("e-mail validated")
restart = False
else :
print("Wrong e-mail")
pws = input("password :\n")
psw_bytes = psw.encode()
mail_bytes = mail.encode()
psw_encrypted_in_bytes = f.encrypt(psw_bytes)
mail_encrypted_in_bytes = f.encrypt(mail_bytes)
mail_encrypted_str = mail_encrypted_in_bytes.decode()
psw_encrypted_str = psw_encrypted_in_bytes.decode()
f = open('a.csv', 'a', newline='')
tup1 = (website, mail_encrypted_str, psw_encrypted_str)
writer = csv.writer(f, delimiter = ';')
writer.writerow(tup1)
print("Saved ;)")
f.close()
return
And here is my output (I have already saved data)
Output (First, you see the name of the ws with the email and the psw encrypted then just the name which is what I want
I finally succeed, instead of using a csv.Reader, i used a csv.DictReader and as all the names i'm looking for are on the same column, i juste have to use the title of the columns.
So here is the code :
with open('mycsv.csv', newline='') as csvfile:
data = csv.DictReader(csvfile)
print("Websites")
print("---------------------------------")
for row in data:
print(row['The_title_of_my_column'])
make list from csv.reader()
rows = [row for row in csv_file]
and now you can get element by identifier using rows as list of lists
rows[id1][id2]
I've been working this problem way too long, please explain to me why the header keeps repeating in my output csv.
I have an input csv with this data:
name,house
"Abbott, Hannah",Hufflepuff
"Bell, Katie",Gryffindor
"Bones, Susan",Hufflepuff
"Boot, Terry",Ravenclaw
The problem requires reversing last and first name, separate name into two columns, and make a new header with 3 columns for the output csv. Here's what I have:
while True:
try:
# open file
with open(sys.argv[1]) as file:
# make reader
reader = csv.reader(file)
# skip first line (header row)
next(reader)
# for each row
for row in reader:
# identify name
name = row[0]
# split at ,
name = name.split(", ")
# create var last and first, identify var house
last = name[0]
first = name[1]
house = row[1]
# writing the new csv
with open(sys.argv[2], "a") as after:
writer = csv.DictWriter(after, fieldnames=["first", "last", "house"])
# HEADER ONLY NEEDS TO OCCUR ONCE
writer.writeheader()
writer.writerow({"first": first, "last": last, "house": house})
sys.exit(0)
my output csv:
first,last,house
Hannah,Abbott,Hufflepuff
first,last,house
Katie,Bell,Gryffindor
first,last,house
Susan,Bones,Hufflepuff
I've tried removing the while loop, unindenting and indenting, writing a row manually with the header names (which caused errors). Please help. Thanks!
You can add a variable that hold whether a header was printed or not, ex write_header
while True:
try:
write_header = True
# open file
with open(sys.argv[1]) as file:
# make reader
reader = csv.reader(file)
# skip first line (header row)
next(reader)
# for each row
for row in reader:
# identify name
name = row[0]
# split at ,
name = name.split(", ")
# create var last and first, identify var house
last = name[0]
first = name[1]
house = row[1]
# writing the new csv
with open(sys.argv[2], "a") as after:
writer = csv.DictWriter(after, fieldnames=["first", "last", "house"])
# HEADER ONLY NEEDS TO OCCUR ONCE
if write_header:
writer.writeheader()
write_header = False
writer.writerow({"first": first, "last": last, "house": house})
sys.exit(0)
See how i used write_header
On an other note, you can refactor your code to open the csv writer before the for loop, write headers there, then write values as you do now without the need to reopen the file each time you want to write a row
sorry if this isn't clear, or if this is simple, I'm a complete newbie at this.
I have this python code:
identer = input("Enter your Student ID... ")
passenter = input("Enter your password... ")
with open("pupil.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
if identer != row["student_id"] or passenter != row["password"]:
print("Wrong ID or Password, try again.")
else:
The line if identer != row["student_id"] or passenter != row["password"]: is throwing the error:
TypeError: list indices must be integers or slices, not str
Is there a solution here I'm blind to? Here is the CSV file, if it helps.
forename,surname,phone_no,email,password,student_id,account_balance,module1,module2
nathan,m,099099,ddd,12345,754,100,,
reg,beg,180,regb,0987,331,100,,
g,b,334,email,911,203,100,,
Edit:
This is my code with dictreader
with open("pupil.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
if identer != row[student_id] or passenter != row[password]:
print("Wrong ID or Password, try again.")
else:
This time it is throwing an error saying "KeyError: 754" 754 being the id
This should work:
with open("pupil.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
if identer != row['student_id'] or passenter != row['password']:
print("Wrong ID or Password, try again.")
else:
# code for handling the else case
You access dictionary elements with strings as key by putting quotes around you column names. I believe you were doing that previously already, but weren’t using the DictReader. This is how you access the rows with it.
I want to check a CSV if it has a value that matches a variable. If it does contain that variable I want to print out 'variable present'
I tried to check each row for matching text of the variable and each field in the row. I do not get an error message but the result is always negative.
import csv
old_name = "random name already present in the table"
with open("data.csv", "r") as csv_file:
fieldnames = ["name", "price"]
csv_reader = csv.DictReader(csv_file, fieldnames=fieldnames)
for row in csv_reader:
for field in row:
if field == old_name:
print("already there")
else:
print("not there")
Output is just 'not there' for each item in the table.
Each row returned by iterating DictReader gives you a dict containing the column name as key, you should do something like:
for row in csv_reader:
if row['name'] == old_name
I'm trying to add a new column by copying col#3 and then append #hotmail to the new column
Here is the script, only problem is that it will not finish processing the input file, it only show 61409 rows in the output file, whereas in the input file there are 61438 rows.
Also, there is an error message (the input file does not have empty line at the end):
email = row[3]
IndexError: list index out of range
inFile = 'c:\\Python27\\scripts\\intake.csv'
outFile = 'c:\\Python27\\scripts\\final.csv'
with open(inFile, 'rb') as fp_in1, open(outFile, 'wb') as fp_out1:
writer = csv.writer(fp_out1, delimiter=",")
reader = csv.reader(fp_in1, delimiter=",")
for col in reader:
del col[6:]
writer.writerow(col)
headers = next(reader)
writer.writerow(headers + ['email2'])
for row in reader:
if len(row) > 3:
email = email.split('#', 1)[0] + '#hotmail.com'
writer.writerow(row + [email])
It looks like you edited the code you received in your earlier answer.
Change
email = email.split('#', 1)[0] + '#hotmail.com'
to
email = row[3].split('#', 1)[0] + '#hotmail.com'