Password Manager Replacing Passwords - python

I want to append the same website accounts. But it is Replacing Passwords when trying to save multiple accounts on the same website. What am I doing wrong?
Here is my Code:
def save():
websites = website_entry.get()
email = user_entry.get()
passwords = password_entry.get()
new_data = {
websites: {
"Email": email,
"Password": passwords,
}
}
if len(websites) == 0 or len(email) == 0 or len(passwords) == 0:
messagebox.showinfo(title="Oops!", message="Please give all the required information's")
else:
try:
with open("data.json", "r") as data_file:
data = json.load(data_file)
except FileNotFoundError:
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4)
else:
data.update(new_data)
with open("data.json", "w") as data_file:
json.dump(data, data_file, indent=4)
finally:
user_entry.delete(0, END)
website_entry.delete(0, END)
password_entry.delete(0, END)

The problem is that you are opening data.json in write versus append mode when you go to add new data to it:
with open("data.json", "w") as data_file:
json.dump(data, data_file, indent=4)
Instead, you should be opening data.json in append mode to avoid overwriting the existing contents of the file:
with open("data.json", "a") as data_file:
json.dump(data, data_file, indent=4)

Related

how to rename json file using python

I would like to save new created json file as a new one with an updated name, for example, the original file name is
update.json
what I want is
{newid_}+update.json
#example:123_update.json
with open("./update.json", "r") as jsonFile:
data = json.load(jsonFile)
data["Id"] = "newid"
with open("./update.json", "w") as jsonFile:
json.dump(data, jsonFile)
Many thanks
You can pass the value of the new ID in the file name using format string.
newId = 'Your ID here'
with open(f"./{newId}_update.json", "w") as jsonFile:
json.dump(data, jsonFile)
Something like this should do the work:
data["Id"] = "newid"
newname = "./"+data["Id"]+"_update.json"
with open(newname, "w") as jsonFile:
json.dump(data, jsonFile)
Right now you are saving the new file under update.json.json.
In the open function, is where you can choose where to write your new file.
So in your case, it could be something like
# Use a f-string to insert the new id into the file name
new_file_path = f"./{data['Id']}_update.json"
with open(new_file_path, "w") as jsonFile:
json.dump(data, jsonFile)
Note that this will not delete the previous file. If you wish to overwrite the previous file, then you can do something like:
import os
file_path = "update.json"
new_file_path = f"./{data['Id']}_update.json"
# Overwrite the content of the old file
with open(file_path, "w") as jsonFile:
json.dump(data, jsonFile)
# Rename it
os.rename(file_path, new_file_path)

How do I use try and else in function in python?

How do I request and export http file to read if file is not present in my directory?
My code :
def data():
try:
with open('sample.json', 'r') as openfile:
json_object = json.load(openfile)
except FileNotFoundError as e:
print(e)
else:
print('Downloading NOW...')
url = 'https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json'
d = requests.get(url).json()
with open("sample.json", "w") as outfile:
json.dump(d, outfile)
print('sym downloaded')
finally:
with open('sample.json', 'r') as openfile:
json_object = json.load(openfile)
print(json_object)
What am i trying?
step 1 : Try : Read file from directory
step 2 : if file not found in directory than get it from url and export
step 3 : than read again
step 4 : if still erorr than print('Error in code Please Check')
else print the read_file
Thank you for taking your time to response my question.
Code:
Use isfile(<file>) instead, it is a better option in this case.
isfile('sample.json') checks if file exists or not.
from os.path import isfile
def data():
file='sample.json'
if isfile(file):
with open(file, 'r') as openfile:
json_object = json.load(openfile)
else:
print('Downloading NOW...')
url = 'https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json'
d = requests.get(url).json()
with open("sample.json", "w") as outfile:
json.dump(d, outfile)
print('sym downloaded')
with open('sample.json', 'r') as openfile:
json_object = json.load(openfile)
print(json_object)

Python pickle module usage

import pickle
data_list = list()
def Add(x):
data_list.append(x)
with open("data.pkl", "wb") as f:
pickle.dump(data_list, f, pickle.HIGHEST_PROTOCOL)
while 1:
abc = input("--->")
if abc == "data":
with open("data.pkl", "rb") as f:
print(pickle.load(f))
else:
Add(abc)
print(data_list)
I saved my list with the pickle module.
After restarting the program, if I query the list contents without adding new data, I can see the records, but if I add new data, I cannot see the old records. Why i can't see old records ?
It's because you are starting the program with an empty list. you should add a function which sync the database if exists on startup
import os
import pickle
# Sync database
if os.path.exists('data.pkl'):
with open("data.pkl", "rb") as f:
data_list = pickle.load(f)
else:
data_list = list()
def Add(x):
data_list.append(x)
with open("data.pkl", "wb") as f:
pickle.dump(data_list, f, pickle.HIGHEST_PROTOCOL)
while 1:
abc = input("--->")
if abc == "data":
with open("data.pkl", "rb") as f:
print(pickle.load(f))
else:
Add(abc)
print(data_list)

Python JSON File Formatting

Hello I am trying to create a JSON file, I am having trouble formatting the file.
Below I will provide the code, and the output.
Code:
def writeToFile(self):
self.json_conceivement = os.path.join("./",'NoobPremeNewEggLogIn.json')
self.accounts = {}
if os.path.exists(self.json_conceivement):
try:
with open(self.json_conceivement) as f:
self.accounts = dict(json.loads(f.read()))
except:
pass
self.accounts = {}
else:
try:
with open(self.json_conceivement) as f:
self.accounts = {}
except:
pass
self.accounts['Profiles'] = []
self.autoSave()
def autoSave(self):
with open(self.json_conceivement, "a", encoding='utf-8') as outfile:
json.dump(dict(self.accounts.items()), outfile,ensure_ascii=False, indent=4)
Output:(if I run it once, expected)
{
"Profiles": []
}
Output:(if i run it twice,incorrect)
{
"Profiles": []
}{}
Wanted output:
{
"Profiles": [{}]
}
Any help would be appreciated
Change this line
with open(self.json_conceivement, "a", encoding='utf-8') as outfile:
to
with open(self.json_conceivement, "w", encoding='utf-8') as outfile:

Python json file modifying

I have a problem.Every timei do this it will just replace the last users wallet.
data = {}
usern = ctx.message.author
usern = str(usern)
data[usern] = []
data[usern].append({
"money": 0
})
Got and answer for it:
with open('config.json', 'r') as infile:
data = json.load(infile) # load from existing
data1 = data
usern = ctx.message.author
usern = str(usern)
data1[usern] = []
data1[usern].append({
"money": 0
})
else: # no file, start from scratch
data = {}
data = {}
usern = ctx.message.author
usern = str(usern)
data[usern] = []
data[usern].append({
"money": 0
})
with open('config.json', 'w') as outfile:
json.dump(data, outfile)
Check whether the file exists & load the existing json structure from it. Change the beginning part of your program to this:
from os.path import isfile
if isfile('config.json'): # check if file exists
with open('config.json', 'r') as infile:
data = json.load(infile) # load from existing
else: # no file, start from scratch
data = {}

Categories

Resources