Delete one object from a JSON file using python - python

#Bot.command()
async def cl(ctx,member:discord.Member = None):
with open("C:\python3\economy.json","r") as f:
json.load(f)
queue.remove(str(member.id))
with open("C:\python3\economy.json","w") as f:
json.dump(f)
I need to delete only highlighted text оn the picture:
json file

There are 3 errors:
You haven't defined queue
There's no such method as dict.remove, you're looking for dict.pop
You're not saving anything into your JSON file
Fixing your code
with open("C:\python3\economy.json", "r") as f:
queue = json.load(f) # defining `queue`
queue.pop(str(member.id)) # removing the key
with open("C:\python3\economy.json", "w") as f:
json.dump(queue, f) # saving into the JSON file

Related

I need help creating a simple python script that stores an attribute value from a custom json file

JSON file looks like this:
{"Clear":"Pass","Email":"noname#email.com","ID":1234}
There are hundreds of json files with different email values, which is why I need a script to run against all files.
I need to extract out the value associated with the Email attribute, which is nooname#email.com.
I tried using import json but I'm getting a decoder error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Script looks like this:
import json
json_data = json.loads("file.json")
print (json_data["Email"]
Thanks!
According to the docs, json.loads() takes a str, bytes or bytearray as argument. So if you want to load a json file this way, you should pass the content of the file instead of its path.
import json
file = open("file.json", "r") # Opens file.json in read mode
file_data = file.read()
json_data = json.loads(file_data)
file.close() # Remember to close the file after using it
You can also use json.load() which takes a FILE as argument
import json
file = open("file.json", "r")
json_data = json.load(file)
file.close()
your script needs to open the file to get a file handle, than we can read the json.
this sample contains code that can read the json file. to simulate this, it uses a string that is identical with the data coming from the file.
import json
#this is to read from the real json file
#file_name = 'email.json'
#with open(file_name, 'r') as f_obj:
#json_data = json.load(f_obj)
# this is a string that equals the result from reading json file
json_data = '{"Clear":"Pass","Email":"noname#email.com","ID":1234}'
json_data = json.loads(json_data)
print (json_data["Email"])
result: noname#email.com
import json
with open("file.json", 'r') as f:
file_content = f.read()
#convert json to python dict
tmp = json.loads(file_content)
email = tmp["Email"]
As already pointed out in previous comments, json.loads() take contents of a file rather than a file.

Remove line from file, inside a loop reading python

I have a weird problem when reading a file named ReadingFile. So what I'm trying to do is read everything that's inside a file named ReadingFile and right after reading a line, remove that line that was read in the ReadingFile.
The code:
import os
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('Test.log')
file_formatter = logging.Formatter('[%(asctime)s]: %(message)s')
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)
def RemoveOneLine(file, ToDelete):
with open(file, 'r') as f:
lines = f.readlines()
with open(file, 'w') as f:
for line in lines:
if line.strip('\n') != ToDelete:
f.write(line)
def Test(filename):
with open(filename, 'r') as a_file:
for line in a_file:
test_line = line.strip()
logger.info('was [{}]'.format(test_line))
RemoveOneLine(filename, test_line)
Test('ReadingFile')
The ReadingFile content, I will upload on Pastebin because it's too big. https://pastebin.com/9kTwv5Kj what's this big list? It's a list of accounts, don't worry.. they are public keys.. no harm can be done knowing the keys.
The problem.
After some time I. get truncated data and wrong data, wrong public keys.. too long public keys or too short, or same lenght keys but non existent in ReadingFile..
As you can see in pastebine the first line is GA25ETO3HJFO4NJLM2PG25WGHWMX35DS4KI7BLY2PA5DTNCDUN2UUSVP when loop reach line GAL7MUG4G3MMO24JKESAMWWIAJT4L7TKX74EONZSB7RKDUGAYSWUQ7JG it starts to get truncated data..
Compared screens, left non changed, right truncated..
What i need is just: Read file -> Read Line -> Remove Line that was read -> Read again first line -> Close program when file is empty.. maybe i did in wrong way, im pretty new to python.
What's wrong?
Try this one. The code is corrected like this:
Adding close() method, each time when finished the file processing.
Adding a missed readlines() method in the Test() function.
[Code]
import os
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
#You can clear log file eatch time using mode='w'
#OR you can use mode='a' to Append it
file_handler = logging.FileHandler('Test.log', mode='w')
file_formatter = logging.Formatter('[%(asctime)s]: %(message)s')
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)
def RemoveOneLine(file, ToDelete):
with open(file, 'r') as f:
lines = f.readlines()
f.close() # we can now close the file after readlines()
with open(file, 'w') as f:
for line in lines:
if line.strip('\n') != ToDelete:
f.write(line)
f.close() # we can close the file now after we have update it
def Test(filename):
with open(filename, 'r') as a_file:
lines_a_file = a_file.readlines() #should add readlines() here
a_file.close() # we can now close the file after readlines()
for line in lines_a_file:
test_line = line.strip()
logger.info('was [{}]'.format(test_line))
RemoveOneLine(filename, test_line)
Test('ReadingFile')

Add a new entry to a json file in Python

I have a json file that works fine, I have a bot command on discord that displays a random entry from it.
The next command I would like to write is on how to add a new entry so that I don't need to do it manually through Atom.
async def addquote(self, ctx, message):
with open('quotes.json','r') as f:
quote = json.load(f)
#quote[str(message)] =
with open('quotes.json', 'w') as f:
json.dump(quote, f)
await ctx.send('Quote added.')
The commented # line is where I'm struggling the most I think.
Jsonfile
Here's a screenshot of the jsonfile, how it looks. I would like to add more "quotes" to it with that function
Thanks a lot
These code worked on my side:
import json
with open('quotes.json','r') as f:
quote = json.load(f)
print(quote)
quote['Quote'].append({
'quote':"test"
})
with open('prefises.json', 'w') as f:
json.dump(quote, f)
with the quotes.json:
{"Quote":[]}
and the prefises.json:
{"Quote": [{"quote": "test"}]}
I fixed my problem by using a list instead of a dictionary in my JSON.
async def addquote(self, ctx, *, message):
with open('quotes.json','r') as f:
quote = json.load(f)
quote.append(message)
with open('quotes.json', 'w') as f:
json.dump(quote, f)
await ctx.send('Quote added.')
The quote.json was cleared and the content was only []
Then writing to it worked.

No JSON object could be decoded ,even when valid json in present in the file

For converting dictionary element to Json and write to a file ,
with open(filename,'w') as f:
if(os.stat(f).st_size == 0):
json.dump(new_data, f)
else:
data = json.load(f)
data.update(new_data)#adding a new dictionary
json.dump(data, f)
i am able to write only one json to the file. When i want to read the exisiting file and then append another set of dictionary , i am unable to do .
Getting ValueError: No JSON object could be decoded tried
json.loads(f), json.load(f)
You should simply read from the file first, if it exists. If it is already empty, or contains invalid JSON, or doesn't exist, initialize data to the empty dict (which is the identity element for the update method).
try:
with open(filename) as f:
data = json.load(f)
except (IOError, ValueError):
data = {}
Then open the file in write mode to write the updated data.
data.update(new_data)
with open(filename, 'w') as f:
json.dump(data, f)

Saving a file in a directory but also being able to print it whenever i needto

I am running Python 3.x. So i have been working on some code for fetching data on currencies names around the world from a currency website to get information which the code is as follows
def _fetch_currencies():
import urllib.request
import json
f = urllib.request.urlopen('http://openexchangerates.org/api/currencies.json')
charset = f.info().get_param('charset', 'utf8')
data = f.read()
decoded = json.loads(data.decode(charset))
dumps = json.dumps(decoded, indent=4)
return dumps
I then need to save it as a file locally but having some issue and cant see where.
Here is the code for saving the currencies:
def save_currencies(_fetch_currencies, filename):
sorted_currencies = sorted(decoded.items())
with open(filename, 'w') as my_csv:
csv_writer = csv.writer(my_csv, delimiter=',')
csv_writer.writerows(sorted_currencies)
They just don't seem to work together apart from when i remove the line ' dumps = json.dumps(decoded, indent=4) ' but i need that line to be able to print the file in text, how do i get around deleting this line and still be able to save and print? How do i also pick where it saves?
Any Help will be great, thank you very much anyone and everyone who answers/reads this.
I may be mistaken, but your "decoded" variable should be declared as global in both functions.
I would actually have _fetch_currencies() return a dictionary, and then I would pass that dictionary on to saved_currencies(currencies_decoded, filename). For example:
def _fetch_currencies():
import urllib.request
import json
f = urllib.request.urlopen('http://openexchangerates.org/api/currencies.json')
charset = f.info().get_param('charset', 'utf8')
data = f.read()
decoded = json.loads(data.decode(charset))
return decoded
def save_currencies(currencies_decoded, filename):
sorted_currencies = sorted(currencies_decoded.items())
with open(filename, 'w') as my_csv:
csv_writer = csv.writer(my_csv, delimiter=',')
csv_writer.writerows(sorted_currencies)
my_currencies_decoded = _fetch_currencies()
save_currencies(my_currencies_decoded, "filename.csv")
Furthermore, if you would like to save your csv file to a certain location in your filesystem, you can import os and use the os.path.join() function and provide it the FULL path. For example, to save your .csv file to a location called "/Documents/Location/Here", you can do:
import os
def save_currencies(currencies_decoded, filename):
sorted_currencies = sorted(currencies_decoded.items())
with open(os.path.join("Documents","Location","Here"), 'w') as my_csv:
csv_writer = csv.writer(my_csv, delimiter=',')
csv_writer.writerows(sorted_currencies)
You can also use a relative path, so that if you're already in directory "Documents", and you'd like to save a file in "/Documents/Location/Here", you can instead just say:
with open(os.path.join("Location", "Here"), 'w') as my_csv:

Categories