skillsmasters
skillsmasters

Reputation: 27

How to save a variable to a text file and retrieve it later?

I am trying to make a program to save passwords. How do I take the input and put it into a text file password.txt? Also how would I retrieve that data in the future and print it out?

def display():
   print ("Do you want to add a password to get a password? get/add")
   response = input()
   if response == "get":
      savingPasswords()

def savingPasswords():
   username = input("Enter username")
   username = open ('password.txt', 'w')
   password = input ("Enter password")
   account = input("What account is this for?")
   print ("Login successfully saved!")


while status == True:
   display()

Upvotes: 1

Views: 1067

Answers (4)

rafalou38
rafalou38

Reputation: 602

You can use Pickle: a default python package to save data on file

use:

######################
#py3
import pickle
#py2
import cpickle
#################


file = "saves/save1.pickle"
#you can specify a  path, you can put another extension to the file but is best to put .pickle to now what is each file

data = {"password":1234, "user":"test"}
#can be any python object :string/list/int/dict/class instance...



#saving data
with open(file,"w", encoding="utf-8") as  file:
    pickle.dump(data, file)


#retriveing data
with open(file,"r", encoding="utf-8") as  file:
    data = pickle.load(file)
    print(data)
    #-->{"password":1234, "user":"test"}
    print(data["password"])
    #-->1234

it will save the data you put in "data" in the file you specify in "file"

more info about pickle

Upvotes: 1

Joshua Hall
Joshua Hall

Reputation: 342

The problem was with your second function. I would advise using with open to open and write to files since it looks cleaner and it is easier to read. In your code you never wrote to the file or closed the file. The with open method closes the file for you after the indented block is executed. I would also recommend writing to something like a csv file for organized information like this so it will be easier to retrieve later.

def display():
    response = input("Do you want to add a password to get a password? (get/add)\n")
    if response.upper() == "GET":
        get_password()
    elif response.upper() == "ADD":
        write_password()
    else:
        print("Command not recognized.")
        exit()


def write_password():
    with open("password.csv", "a") as f:
        username = input("Enter username: ")
        password = input("Enter password: ")
        account = input("What account is this for? ")
        f.write(f"{username},{password},{account}\n")  # separates values into csv format so you can more easily retrieve values
    print("Login successfully saved!")


def get_password():
    with open("password.csv", "r") as f:
        username = input("What is your username? ")
        lines = f.readlines()
        for line in lines:
            if line.startswith(username):
                data = line.strip().split(",")
                print(f"Your password: {data[1]}\nYour Account type: {data[2]}")


while True:
    display()

Upvotes: 1

kederrac
kederrac

Reputation: 17322

you can store your data as a json:

import json
import os

# data will be saved base on the account
# each account will have one usernae and one pass


PASS_FILE = 'password.json'

def get_pass_json_data():
    if os.path.isfile(PASS_FILE):
        with open(PASS_FILE) as fp:
            return json.load(fp)

    return {}

def get_pass():
    account = input("What account is this for?")
    data = get_pass_json_data()

    if account not in data:
        print('You do not have this account in the saved data!')

    else:
        print(data[account])

def savingPasswords():
    username = input("Enter username")
    password = input ("Enter password")
    account = input("What account is this for?")

    data = get_pass_json_data()

    # this will update your pass and username for an account
    # if already exists

    data.update({
        account: {
            'username': username,
            'password': password
        }
    })

    with open(PASS_FILE, 'w') as fp:
        json.dump(data, fp)


    print ("Login successfully saved!")

actions = {
    'add': savingPasswords,
    'get': get_pass
}

def display():
    print("Do you want to add a password to get a password? get/add")
    action = input()

    try:
        actions[action]()
    except KeyError:
        print('Bad choice, should be "get" or "add"')

while True:       
    display()

Upvotes: 1

Gabio
Gabio

Reputation: 9484

Write to a file:

password="my_secret_pass"
with open("password.txt","w") as f:
    f.write(password)

to read the password from the file, try:

with open("password.txt","r") as f:
    password = f.read()

Upvotes: 1

Related Questions