Pickle only picking up some of the list - python

If I have a list of seven items with similar names, it will only populate six of them in the pickle file. Six seems to be where the issues start, but if I move that up to nine items, it will show eight.
In the code, it does not show them under the full iteration of data2 in function access_passwords. But they will pull accurately under function access_one_pw. So they're populating, but the iteration that should be printing the device + the password does not seem to be working correctly.
def add_passwords():
data = []
newdata = []
pw_file_r = open('K:\\Downloads\\Chrome Downloads\\pickle.txt', 'rb') # modify to local folder and create
# pickle.txt document
while True:
try:
data.append(pickle.load(pw_file_r))
except EOFError:
break
pw_file_r.close()
pwordN = int(input('Enter the number of devices to name: '))
for i in range(pwordN):
raw = input('Enter device name ' + str(i) + ' : ')
newdata.append(raw)
for x in newdata:
global keyvar
data.append(x)
pw_file_w = open('K:\\Downloads\\Chrome Downloads\\pickle.txt', 'ab') # modify to local folder
pickle.dump(x, pw_file_w)
pw_file_r.close()
newpass = getpass.win_getpass(prompt='Enter the password for the device ' + x + ': ', stream=None)
newpass_to_bytes = bytes(newpass, 'utf-8')
key = base64.urlsafe_b64encode(bytes(keyvar, 'utf-8'))
cipher_suite = Fernet(key)
ciphered_text = cipher_suite.encrypt(newpass_to_bytes)
db_update = shelve.open('K:\\Downloads\\Chrome Downloads\\device_shelf.db') # modify to local folder
try:
db_update[x] = ciphered_text
finally:
db_update.close()
def access_passwords():
data2 = []
data2.clear()
global keyvar
pw_file_r = open('K:\\Downloads\\Chrome Downloads\\pickle.txt', 'rb') # modify to local folder
while 1:
try:
data2.append(pickle.load(pw_file_r))
except EOFError:
break
pw_file_r.close()
for x1 in data2:
db_read = shelve.open('K:\\Downloads\\Chrome Downloads\\device_shelf.db') # modify to local folder
try:
device = db_read[x1]
finally:
db_read.close()
key = base64.urlsafe_b64encode(bytes(keyvar, 'utf-8'))
cipher_suite = Fernet(key)
ciphered_text = device
unciphered_text = (cipher_suite.decrypt(ciphered_text))
plaintxt = bytes(unciphered_text).decode("utf-8")
print('The device ' + x1 + ' has a password of ' + plaintxt)
restart = input('Do you want to restart the program? [Yes/No]: ')
if restart == 'Yes':
frun()
else:
pass

Related

Encrypted password manager. A file sanvalley.txt which has to show encrypted version of the code and later decrypt it as output. file shows input raw

import string
from cryptography.fernet import Fernet
'''Creation and Calling of the encryption(discarded after calling)'''
'''def write_key():
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)**strong text**
write_key()'''
'''my function to decrypt the encoded password'''
def decrp():
with open('sanvalley.txt', 'r') as secret:
for row in secret:
print(row.read(fer.decrypt(U.encode()).decode()) + '|' + (fer.decrypt(P.encode().decode()) + '\n'))
def load_key():
with open("key.key", "rb") as alpha_key:
real_key = alpha_key.read()
return real_key
master_pass = input('Lost in Soul Sand be everything, but the KEY! \n')
while master_pass == 'Soul':
key = load_key() + master_pass.encode()
fer = Fernet(key)
action = input('Add/View Soul?').lower().strip()
if action == None:
quit
try:
if action == 'add':
U = input('Soulname: ')
P = input('Soul Sand: ')
with open('sandvalley.txt','a') as f:
beta = str(f)
secret = fer.encrypt(beta.encode())
output = f.write(secret)
print('Souls saw the light')
print('Souls have ceased!')
if action == 'view':
with open('sanvalley.txt', 'r') as secret:
for row in secret:
decrp()
if action != 'view' or 'add':
print ('End')
except:
input == None
break
break
'''code does save it to the file but its not encrypted , neitther can i decrypt'''

Numbering or counting the appended lines in python

I would like to count or add numbers to the file everytime I add something to it.
My file is consist of
Account|Username|Password
I would like to have it like this whenever the user adds another account.
# Account Username Password
1 Facebook Name Pass
My code of adding account is this
def add_account():
acc = input("Enter the name of your account.")
username = input(f"Enter the username of your {acc}")
password = input(f"Enter the password of your {acc}")
ask = input(f" Do you like to save {acc} credentials? Y|N")
if ask == "Y":
with open("myfile.txt", "a") as file:
file.write("" + "|" + acc + "|" + username + "|" + password)
file.close()
add_accout()
def view_account():
file = open("myfile.txt", "r")
line = file.readline()
for line in file:
a, b, c, d = line.split("|")
d = d.strip()
print(formatStr(a), formatStr(b), formatStr(c), formatStr(d))
view_account()
def formatStr(str):
nochars = 15
return str + (" "*(nochars - len(str))
How can I count the appended lines?
As jarmod is suggesting in the comments, you can use a global counting variable to number each added account:
counting = 0
def add_account():
global counting
acc = input("Enter the name of your account.")
username = input(f"Enter the username of your {acc}")
password = input(f"Enter the password of your {acc}")
ask = input(f" Do you like to save {acc} credentials? Y|N")
if ask == "Y":
counting += 1
with open("myfile.txt", "a") as file:
file.write("" + acc + username + password + str(counting))
file.close()
add_account()
If you need to be able to quit the program, restart it later, and have it discover the last account number stored in your database, then you can do this as follows to calculate the next free account number:
SEPARATOR = '|'
def next_account_number():
next_num = 1
with open("myfile.txt", "r") as f:
# Read lines discarding empty lines
lines = f.read().splitlines()
lines = list(filter(lambda x: x != "", lines))
if len(lines) > 1:
account = lines[-1].split(SEPARATOR)
try:
next_num = int(account[0]) + 1
except ValueError:
pass
return next_num
print("Next account number:", next_account_number())

My Crypto is not working right, it keeps resetting

I was working on a cryptocurrency and everything else works but this, you can have a mine once, but then you can't after one time because the balance is the same. It should be simple. I need help with the balance and saving it and being able to mine more than once,
You will probly be able to fix this instantly
import os
import time
from anthonys_balance import lbalance
balance = 1
user = input("Username:")
f = open(user + "'s file", "w")
username = user
ubalance = balance
userbalance = f'{balance}{username}'
log = f'{user} has a balance of {lbalance} Coinon'
y=f'{user}s_balance.py'
if os.path.exists(y):
if os.path.isfile(y):
print("file is present")
else:
f = open(user + "s_balance.py", "x")
f.write (f'lbalance = {ubalance}')
f.close()
f = open(user + "'s file", "w")
f.write(str(log))
f.close()
userfile = user + "s_balance.txt"
os.system("clear")
def select():
from anthonys_balance import lbalance
print(f'{user} has a balance of {lbalance} Coinon')
print("Mine = 1")
print("Send = 2")
options = input("Selection:")
if options == "1":
def mine():
x = 1
if x == 1:
time.sleep(3)
#import user + "'s balance.py"
from anthonys_balance import lbalance
lnbalance = lbalance +1
f = open(user + "'s file", "w")
f.write(f'{user} has a balance of {lnbalance +1} Coinons')
f.close()
f = open(f'{user}s_balance.py', "w")
f.write(f'lbalance = {lnbalance +1}')
f.close()
print(f'{user} has a balance of {lnbalance +1} Coinons')
print("mine success")
input("Continue?")
f = open(user + "'s file", "w")
f.write(f'{user} has a balance of {lnbalance +1} Coinons')
f.close()
mine()
mine()
pass
select()
I didn't run it but I see few problems
you have mess in code. To make code more readable you could
put mine() outside select(),
convert some code into function - ie. read_data, save_data, log,
put all functions directly after import
send values to function as arguments
(see more in PEP 8 -- Style Guide for PythonCode)
you use import to load data but import reads file only once and it remember it - so it doesn't load again the same file. Python assumes that code doesn't change and data should be in files like .txt, .json, .ini, .yaml, `pickle, etc. or in database
This is my version with all changes.
I keep balance in dictionary data and I save it in .json - so I can keep other information data and save it in file - ie. username.
I load data only once - at start - and later I uses value which I have in memory and only I save new value in file. If there is no file at start then I create new one with default values.
I use while True to run code many times and user may select X to exit it.
import os
import time
import json
import datetime
# --- functions ---
def log(username, text):
dt = datetime.datetime.now().strftime('%Y.%m.%d %H:%M.%S')
filename = f'{username}.log'
with open(filename, "a") as f: # append
f.write(f'{dt} {text} \n')
def load_data(username):
filename = f'{username}.json'
if os.path.exists(filename) and os.path.isfile(filename):
with open(filename) as f:
data = json.load(f)
else:
data = None
return data
def save_data(username, data):
filename = f'{username}.json'
with open(filename, 'w') as f:
json.dump(data, f)
def select(username, data):
while True:
print(f'{username} has a balance of {data["balance"]} Coinons')
print("1. Mine")
print("2. Send")
print("X. Exit")
answer = input("Selection:")
answer = answer.upper().strip()
if answer == "X":
return
elif answer == "1":
mine(username, data)
elif answer == "2":
print('not created')
#send(username, data)
def mine(username, data):
time.sleep(3)
data['balance'] += 1
save_data(username, data)
log(username, f'{username} has balance {data["balance"]} Coinon')
print(f'{username} has a balance of {data["balance"]} Coinons')
print("mine success")
input("Press any key to continue.")
# --- main ---
username = input("Username: ")
# load data from file or use default value
data = load_data(username)
if not data:
data = {'balance': 1, "username": username}
save_data(username, data)
log(username, f'{username} has balance {data["balance"]} Coinon')
os.system("clear")
select(username, data)

Python program doesn't write in a file

The user gives input to the program and it should write it in a file There is a problem with uploading it to the txt file.
Plan = open("Plan.txt", "r")
content = Plan.read()
Plan_lista = content.split(",")
Przedmioty = []
Przedmioty = list(set(Plan_lista))
Przedmioty.remove("")
Plan.close()
#Dodawanie linków do listy
Linki = open("Linki.txt", "w+")
print("\n" + "Podaj Link do:")
a=0;
for i in range(len(Przedmioty)):
print (Przedmioty[a], end = "\r")
link = input(": ")
Linki.write(Przedmioty[a] + "," + link)
if ( a != len(Przedmioty)-1):
Linki.write(", ")
a+=1

How would I overwrite the fav_genre of the user in this code

So I'm developing a code for a very basic music app, Every users information is saved into the database using the following format:
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n' )
now I want to read the existing information of a particular user and allow them to change their fav_genre. Below is my failed attempt to do so:
textfile = 'user_DB.txt'
def a():
username = input('name?: ')
with open(textfile, 'r+') as textIn:
for line in textIn:
information = line.split(" : ")
if information[0] == username:
print('Your current genre is:',information[5])
new_genre = input('what would you like your new genre to be?')
information[5] = new_genre
textIn.write(information[5]=new_genre)#this line
print('new genre is saved to',information[5])
break
elif information != username:
print('Name not found, Please try again')
a()
else:print('invalid')
break
textIn.close()
a()
The line with the comment #this line is where I think the error is occouring as I want to overwrite the previous value of fav_genre for that specific user with the new one.Any ideas on what I could do different to make this work?
Basically change that line to:
textfile.write(' : '.join(information.values()) + '\n' )
So full code:
textfile = 'user_DB.txt'
updated_textfile = 'user_DB_Updated.txt'
def a():
username = input('name?: ')
updated_lines = []
with open(textfile, 'r+') as textIn:
for line in textIn:
information = line.split(" : ")
updated_lines.append(line)
if information[0] == username:
print('Your current genre is:',information[5])
new_genre = input('what would you like your new genre to be?')
information[5] = new_genre
updated_lines[-1] = ' : '.join(information) + '\n'
print('new genre is saved to ',information[5])
break
elif information != username:
print('Name not found, Please try again')
a()
else:print('invalid')
break
with open(updated_textfile, 'w+') as out_text:
out_text.write(''.join(updated_lines))
textfile.close()
a()

Categories