Home > OS >  How to edit a cell using and saving it to a file pandas (Python)
How to edit a cell using and saving it to a file pandas (Python)

Time:03-21

I need help, I don't know hot wo change the value of a cell and save it to the file. I just want to make it so when the user has verified the o changes to 1 in the verified column. The information looks weird because it is encrypted. All of the code for verification and cell stuff can be found in the Verify() function. The csv file: enter image description here

The whole code:

import pandas as pd
import re
import csv
import smtplib
import math
import random
from email.message import EmailMessage
#====================================================================================================#
def Register():
    
    firstname = input("Enter your first name: ").lower()
    
    surname = input("Enter your surname: ").lower()
    
    age = input("Enter your age: ")
    if not str.isdecimal(age):
        print("Age must be a number. Please try again.")
        age = input("Enter your age: ")
            
    email = input("Enter your email: ").lower()
    regex = "^[a-z0-9] [\._]?[a-z0-9] [@]\w [.]\w{2,3}$"
    if not re.search(regex, email):
        print("Invalid email please try again.")
        email = input("Enter your email: ").lower()
        
    password = input("Enter a strong password: ")
    if len(password) < 6:
        print("Password should be between 6 to 18 characters long.")
        password = input("Enter a strong password: ")

    username = firstname[:1]   surname   age
    username.lower()
        
    print("\nYour username is: "    username   "\nYour email is: "   email   "\nYour password is: "   password   "\nYour firstname is: "   firstname   "\nYour surname is: "   surname   "\nYour age is: "   age)
    
    encryptedFirstname = "".join(chr(ord(char) 3) for char in firstname)
    encryptedSurname = "".join(chr(ord(char) 3) for char in surname)
    encryptedAge = "".join(chr(ord(char) 3) for char in age)
    encryptedEmail = "".join(chr(ord(char) 3) for char in email)
    encryptedPassword = "".join(chr(ord(char) 3) for char in password)
    encryptedUsername = "".join(chr(ord(char) 3) for char in username)
    
    verified = "0"
    
    AccountInfo = [encryptedFirstname, encryptedSurname, encryptedAge, encryptedEmail, encryptedPassword, encryptedUsername, verified]
    
    if not str.isdecimal(age) or len(password) < 6 or not re.search(regex, email):
        print("Error occured, please make sure all your details are valid.")
        MainMenu()
    else:
        try:
            open("Accounts.csv", "x")
            with open("Accounts.csv", "a", newline = "") as file:
                writer = csv.writer(file)
                writer.writerow(["Firstname", "Surname", "Age", "Email", "Password", "Username, Verified"])
                writer.writerow(AccountInfo)
                file.close()
                print("Account successfully made. Please verify your email now.")
                MainMenu()
        except:
            with open("Accounts.csv", "a", newline = "") as file:
                writer = csv.writer(file)
                writer.writerow(AccountInfo)
                file.close()
                print("Account successfully made. Please verify your email now.")
                MainMenu()
#====================================================================================================#
def Login():
    
    User0 = input("Username: ").lower()
    Pass0 = input("Password: ")
    
    encryptedPassword = "".join(chr(ord(char) 3) for char in Pass0)
    encryptedUsername = "".join(chr(ord(char) 3) for char in User0)
    
    try:
        file = open("Accounts.csv", "r")
    except:
        print("Account doesn't exist. Please register an account.")
        MainMenu()
        
    detailsList = []
    line = 0
    for line in file:
        detailsList.append(line.rstrip('\n').split(","))
        
    loggedIn = 0
    
    for details in detailsList:
        if encryptedUsername == details[5] and encryptedPassword == details[4] and details[6] == "0":
            loggedIn = 1
            break
        if encryptedUsername == details[5] and encryptedPassword == details[4] and details[6] == "1":
            loggedIn = 2
            break
        
    if loggedIn == 1:
        print("You need to verify your account.")
        MainMenu()
    if loggedIn == 2:
        print("Successfully logged in.")
        MainMenu()
    elif loggedIn == 0:
        print("Incorrect details.")
        MainMenu()
#====================================================================================================#
def Verify():
    
    User1 = input("Username: ").lower()
    Pass1 = input("Password: ")
    encryptedUsername1 = "".join(chr(ord(char) 3) for char in User1)
    encryptedPassword1 = "".join(chr(ord(char) 3) for char in Pass1)
        
    try:
        file = open("Accounts.csv", "r")
    except:
        print("Account doesn't exist. Please register an account.")
        MainMenu()
            
    detailsList = []
    line = 0
    for line in file:
        detailsList.append(line.split(","))

    loggedIn = False

    for details in detailsList:
        if encryptedUsername1 == details[5] and encryptedPassword1 == details[4]:
            
            decryptedEmail = "".join(chr(ord(char)-3) for char in details[3])
            loggedIn = True
            UserEmail = decryptedEmail
            break
        
    LineNumber = 0
    with open("Accounts.csv", 'r') as file:
        for line in file:
            LineNumber  = 1
            if encryptedUsername1 in line:
                break

    if loggedIn == True:
        
        print("Verifying Email Address...")
        
        digits = "0123456789"
        CODE = ""
        msg = EmailMessage()

        smtp = smtplib.SMTP("smtp.gmail.com", 587)

        for i in range(6):
            CODE  = digits[math.floor(random.random()*10)]

        msg.set_content(f"Your code is: {CODE}\nThis code expires in 5 minutes.")
        msg["Subject"] = "PyDatabase: Verification"
        msg["From"] = "[email protected]"
        msg["To"] = UserEmail

        smtp.starttls()
        smtp.login("[email protected]", "password")
        smtp.send_message(msg)
        smtp.quit()

        InputedCode = input("Enter Your Code >>> ")

        if InputedCode == CODE:
            print("Verified!")
            
            LineNumber = LineNumber - 1
            DataFrame = pd.read_csv("Accounts.csv")
            Pos = DataFrame.loc[LineNumber, "Verified"]
            print(Pos)
            
        else:
            print("Wrong code, try again!")
            MainMenu()
    else:
        print("Incorrect password or username. Please try again.")
        MainMenu()
#====================================================================================================#
def MainMenu():
    
    print("#------------------#"   "\n|   1 - Register   |"   "\n|    2 - Login     |"   "\n|    3 - Verify    |"   "\n#------------------#")
    
    choice = input(">>> ")
    
    if choice == "1":
        Register()
    elif choice == "2":
        Login()
    elif choice == "3":
        Verify()
    else:
        print("Invalid choice.")
#====================================================================================================#
MainMenu()

CodePudding user response:

Use df.loc[desired_row, desired_column] = specified_value to set the value, and use pd.to_excel(desired_file_name) to save the file.

CodePudding user response:

I fix it just had to subtract 2 from the line number to get to the right line in the verify function.

LineNumber -= 2

  • Related