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:
Related
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)
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)
I have scraped six different people's followers list from instagram and trying to get the usernames of people that are same in all six accounts but so far it is not accurate so any help would be appreciated.
Here is my code to open and read through json files with followers list and sort them in a dictionary according to their first two letters and compare them
import json
with open('./JSONs Old/A.json', 'r', encoding='utf-8') as f:
A = json.load(f)
with open('./JSONs Old/B.json', 'r', encoding='utf-8') as f:
B = json.load(f)
with open('./JSONs Old/C.json', 'r', encoding='utf-8') as f:
C = json.load(f)
with open('./JSONs Old/D.json', 'r', encoding='utf-8') as f:
D = json.load(f)
with open('./JSONs Old/E.json', 'r', encoding='utf-8') as f:
E = json.load(f)
with open('./JSONs Old/F.json', 'r', encoding='utf-8') as f:
F = json.load(f)
with open('./JSONs Old/G.json', 'r', encoding='utf-8') as f:
G = json.load(f)
Als = {}
Bls = {}
Cls = {}
Dls = {}
Els = {}
Fls = {}
Gls = {}
# Loop For A
for each in A:
if each['id'][:2] in Als.keys():
Als[each['id'][:2]].append(each)
else:
Als[each['id'][:2]] = [each]
# Loop For B
for each in B:
if each['id'][:2] in Bls.keys():
Bls[each['id'][:2]].append(each)
else:
Bls[each['id'][:2]] = [each]
# Loop For C
for each in C:
if each['id'][:2] in Cls.keys():
Cls[each['id'][:2]].append(each)
else:
Cls[each['id'][:2]] = [each]
# Loop For D
for each in D:
if each['id'][:2] in Dls.keys():
Dls[each['id'][:2]].append(each)
else:
Dls[each['id'][:2]] = [each]
# Loop For E
for each in E:
if each['id'][:2] in Els.keys():
Els[each['id'][:2]].append(each)
else:
Els[each['id'][:2]] = [each]
# Loop For F
for each in F:
if each['id'][:2] in Fls.keys():
Fls[each['id'][:2]].append(each)
else:
Fls[each['id'][:2]] = [each]
# Loop For G
for each in G:
if each['id'][:2] in Gls.keys():
Gls[each['id'][:2]].append(each)
else:
Gls[each['id'][:2]] = [each]
matchls = []
for i in B:
if (i['id'][:2] in Als.keys()) and (i['id'][:2] in Cls.keys()) and (i['id'][:2] in Dls.keys()) and (i['id'][:2] in Els.keys()) and (i['id'][:2] in Fls.keys()) and (i['id'][:2] in Gls.keys()):
matchls.append(i)
print(matchls)
The Json files have list of all the followers a person have on their instagram page and list container two key value pairs like following
[
{
"name": "Name1",
"id": "username1"
},
{
"name": "Name2",
"id": "username2"
}
]
i want to check if id from one file is in other five files too.
Thanks in Advance.
Here's one way to do it without sorting:
Using this function you can see if a follower's id is in any other json lists
# (param 1) follower: a single dict with including a key 'id'
# (param 2) follower_lists: list of loaded json files to check an id match
def compareFollowers(follower, follower_lists):
for list in follower_lists: # loop through each json file
if not any(follower['id'] == f['id'] for f in list): # check if the id is the same as another from the list
return False # if there is no common ids, return False
return True # if every list had a common id return True
FYI The any() function returns a boolean value:
True if at least one element of an iterable is true
False if all elements are false or if an iterable is empty
to print all common followers between all files you can do this:
import json
with open('./JSONs Old/A.json', 'r', encoding='utf-8') as f:
A = json.load(f)
with open('./JSONs Old/B.json', 'r', encoding='utf-8') as f:
B = json.load(f)
with open('./JSONs Old/C.json', 'r', encoding='utf-8') as f:
C = json.load(f)
with open('./JSONs Old/D.json', 'r', encoding='utf-8') as f:
D = json.load(f)
with open('./JSONs Old/E.json', 'r', encoding='utf-8') as f:
E = json.load(f)
with open('./JSONs Old/F.json', 'r', encoding='utf-8') as f:
F = json.load(f)
with open('./JSONs Old/G.json', 'r', encoding='utf-8') as f:
G = json.load(f)
follower_lists = [B, C, D, E, F, G] # include every list but the first
for follower in A: # loop through the first list and compare each follower's id
if compareFollowers(follower, follower_lists):
print(follower)
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 = {}
I have the following code which prints the object as CSV:
title = ['Username', 'Name', 'Job']
for x in title:
print(x, end =",")
for d in data:
line = d.get_username() + "," + d.get_name() + "," + d.get_role()
print(line)
I get:
Username,Name,Job
rob,robert,developer
danny21,danny,developer
I want to print the same data as JSON in order to get:
[
{
"Username":"rob",
"Name":"robert",
"Job":"developer"
},
{
"Username":"danny21",
"Name":"danny",
"Job":"developer"
}
]
From previous topics I learn that we can use json.dumps but I'm not sure if it helps in this case.
What is the proper way to achieve it?
You could simply do:
l = []
for d in data:
user_dictionary = {}
user_dictionary[title[0]] = d.get_username()
user_dictionary[title[1]] = d.get_name()
user_dictionary[title[2]] = d.get_role()
l.append(user_dictionary)
to get a json like file.
You can also avoid appending and do:
def get_user_data(user):
user_dictionary = {}
user_dictionary[title[0]] = d.get_username()
user_dictionary[title[1]] = d.get_name()
user_dictionary[title[2]] = d.get_role()
return user_dictionary
l = list(map(get_user_data, data))
You can use json.dump to dump l in a file
import json
with open('data.json', 'w') as outfile:
json.dump(l, outfile)