Vedagya Jha
Vedagya Jha

Reputation: 17

How to convert a list to a file and the load that file into a list again?

I am trying to create a lock which can only be opened with a password in python. You can also create an account to login to the lock. How do I save accounts to a list and access them again when I want to login? This is what I have tried:

from sys import exit
import re

def num_there(s):
    return any(i.isdigit() for i in s)

def special_character_check(String):
    rex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
    search = rex.search(String)
    if search == None:
        print('This password has no special characters')
        exit()

f = open('file.txt', 'w')
e = open('file2.txt', 'w')
    
login_signup = input('Do you want to login or sign up?')
available_accounts_usernames = [f]
available_accounts_passwords = [e]

content = available_accounts_usernames
content2 = available_accounts_passwords

login_username = ''
login_password = ''

signup_username = ''
signup_password = ''
signup_confirm_password = ''

if login_signup in ('login', 'Login'):
    login_username = input('Please enter your username')
    login_password = input('Please enter your password')
    if login_username not in (available_accounts_usernames) or login_password not in (available_accounts_passwords):
        print('Access denied')
        exit()
    if login_username in (available_accounts_usernames) and login_password in (available_accounts_passwords):
        print('Access granted')
        exit()

if login_signup in ('sign up', 'Sign up'):
    signup_username = input('Please enter a username. This username will be asked if you want to login')
    signup_password = input('Please enter a password. You will be asked to confirm your password')
    if len(signup_password) < 8:
        print('This password should be more than 8 characters. PLease enter your info again.')
        exit()
    if num_there(signup_password) == False:
        print('This password has no number')
        exit()

    if num_there(signup_password) == True:       
        special_character_check(signup_password)
        signup_confirm_password = input('Please confirm your password')
        if signup_password == signup_confirm_password:
            available_accounts_usernames.append(signup_username)
            available_accounts_passwords.append(signup_password)   
            print('Your account has been created. Please login to access it.')
        if signup_password != signup_confirm_password:
            print("These passwords don't match. Please enter your info again")
            exit()

content = available_accounts_usernames
content2 = available_accounts_passwords

f.write(str(content))
e.write(str(content2))

It just doesn't work. Sorry if its a long question. I am new to python

Upvotes: 1

Views: 75

Answers (2)

amaank404
amaank404

Reputation: 1128

To solve the problem of storing and reading data you can use some data format such as pickle, json, yaml, toml. But for the simplicity and for the most common data format we will use json. Now, json comes with the python standard library by default and here is some sample json files if you want to know how json looks:

{
  "name": "xcodz",
  "languages": ["python", "html", "css"],
}
[
  "eggs",
  "bread",
  "wheat",
  {
    "name": "CustomObject",
    "cost": 1000
  },
  "noodles"
]

So how does files work. you can open a file using open method.

file = open('MyFile.txt', 'r')  # 'r' can be replaced with different modes

file.read()  # read all the contents

file.write('some content')  # works only when mode is 'w', 'wb', 'w+b', 'a', 'ab', 'a+b'

file.seek(0)  # change the position

now for your purpose here is the json code:

from sys import exit
import re
import json
import os  # For creating defaults

def num_there(s):
    return any(i.isdigit() for i in s)

def special_character_check(String):
    rex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
    search = rex.search(String)
    if search == None:
        print('This password has no special characters')
        exit()

if not os.path.isfile('database.json'):
    with open('database.json', 'w') as f:
        f.write('{"usernames": [], "passwords": []}')

with open('database.json', 'r') as f:
    data = json.load(f)
    available_accounts_usernames = data['usernames']
    available_accounts_passwords = data['passwords']
    
login_signup = input('Do you want to login or sign up?')

content = available_accounts_usernames
content2 = available_accounts_passwords

login_username = ''
login_password = ''

signup_username = ''
signup_password = ''
signup_confirm_password = ''

if login_signup in ('login', 'Login'):
    login_username = input('Please enter your username')
    login_password = input('Please enter your password')
    if login_username not in (available_accounts_usernames) or login_password not in (available_accounts_passwords):
        print('Access denied')
        exit()
    if login_username in (available_accounts_usernames) and login_password in (available_accounts_passwords):
        print('Access granted')
        exit()

if login_signup in ('sign up', 'Sign up'):
    signup_username = input('Please enter a username. This username will be asked if you want to login')
    signup_password = input('Please enter a password. You will be asked to confirm your password')
    if len(signup_password) < 8:
        print('This password should be more than 8 characters. PLease enter your info again.')
        exit()
    if num_there(signup_password) == False:
        print('This password has no number')
        exit()

    if num_there(signup_password) == True:       
        special_character_check(signup_password)
        signup_confirm_password = input('Please confirm your password')
        if signup_password == signup_confirm_password:
            available_accounts_usernames.append(signup_username)
            available_accounts_passwords.append(signup_password)   
            print('Your account has been created. Please login to access it.')
        if signup_password != signup_confirm_password:
            print("These passwords don't match. Please enter your info again")
            exit()

content = available_accounts_usernames
content2 = available_accounts_passwords

with open('database.json', 'w') as f:
    json.dump({'usernames': content, 'passwords': content2}, f)

More info at https://docs.python.org/3.9/library/json.html

Upvotes: 1

DeGo
DeGo

Reputation: 791

You might want to use pickle files instead.

import pickle as pkl

# Write to file
with open("accounts.pkl","wb") as f:
    pkl.dump(accounts, f) # accounts is the list

# Read the file
with open("accounts.pkl","rb") as f:
    accounts = pkl.load(f)

Upvotes: 1

Related Questions