Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

pandas - Python custom function reseting csv file

I am trying to make a login system sort of program but whenever there is more than 1 line of data the code resets the entire CVS file. I need someone to help me with why it's happening. It happens when I choose opt == 2 and search for the name entered 2nd onwards...

reading the CSV file:

try:
    df = pd.read_csv('accounts.csv')
    for i in range(len(df['name'])):
        names.append(df['name'][i])
        balances.append(df['balance'][i])
        dec_pass = bytes(df['password'][i], 'utf-8')
        f = Fernet(key)

        decrypted = f.decrypt(dec_pass)
        decrypted = decrypted.decode()
        passwords.append(decrypted)
except:
    with open('accounts.csv', 'w') as f:
        f.write(',name,balance,password')


names = []
balances = []
passwords = []


def name_ser(name):
found = False
for i in range(len(names)):
    if names[i] == name:
        found = True
        return found, names.index(name)
    else:
        found = False
        return found 


def main_menu():
print('Welcome!
Please Choose from the following options...')
print('1: Create an account
2: Login ')
opt = int(input('Enter Your Choice: '))
if opt == 1:
    name_search = input('Enter Name... ')
    found, _ = name_ser(name_search)
    if found == True:
        print("Account Already excites!")
    else:
        acc_creation(name_search)
        print('Account created!')
if opt == 2:
    name_search = input('Enter your login name: ')
    found, indx = name_ser(name_search)
    if found == True:
        password = input('Enter your password: ')
        dec_pass = bytes(passwords[indx], 'utf-8')
        f = Fernet(key)
        decrypted = f.decrypt(dec_pass)
        decrypted = decrypted.decode()
        if password == decrypted:
            print('Logged in!')
        else:
            print('Invalid username or password')

before: before the reset

after: after the reset

the other thing is when I try to create more than 2 accounts it gives an error and also resets the CSV file. it works fine for the first 2 accounts but gives an error on the second one.

def acc_creation(name):
    names.append(name)
    balances.append(0)
    password_enter = input('Create a Password: ')
    encry_p = password_enter.encode()
    f = Fernet(key)

    encry_pass = f.encrypt(encry_p)
    encry_pass = encry_pass.decode('ascii')
    passwords.append(encry_pass)
    new_df = pd.DataFrame(np.column_stack([names, balances, passwords]),
                          columns=['name', 'balance', 'password'])
    new_df.to_csv('accounts.csv', encoding='utf-8', sep=',',
                  header=True, na_rep=0, index=True)

Error:

Traceback (most recent call last):
  File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 91, in <module>
    main_menu()
  File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 79, in main_menu
    acc_creation(name_search)
  File "/Users/darkmbs/VS-Code/FirstPythonProject/accounts.py", line 54, in acc_creation
    new_df = pd.DataFrame(np.column_stack([names, balances, passwords]),
  File "<__array_function__ internals>", line 5, in column_stack
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/numpy/lib/shape_base.py", line 656, in column_stack
    return _nx.concatenate(arrays, 1)
  File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 2 and the array at index 2 has size 1
question from:https://stackoverflow.com/questions/65617285/python-custom-function-reseting-csv-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe this may possibly be tied to the name_ser method but cannot be totally sure without seeing what it is doing.

What CSV library are you using? CSV? Panda?

Also, you may want to try adding a return value to the name_ser method to return the index and not have to go through the list again to match it to the password.

Good luck!

--- Edit ---

Every time that you are executing it is opening up the file again and re-writing: ,name,balance,password

If you are wanting to execute more than once, you will need to either:

  1. Write a while loop for main where it will continuously call main_menu()
  2. Check to see if the CSV already exists. If it does, open in read and copy everything and paste it into a new writeable CSV. If it doesn't, move to create the new writeable CSV.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...