Does anybody know why this code doesnt work? We are trying to create a json file and write some information in it. The aim is to create a user account, save the password and name in a json file and then login and go on with other functions. See the code below. Any help appreciated!!
player_data_file = 'player_portfolio.json'
with open(player_data_file, 'r') as f:
if os.stat(player_data_file).st_size == 0:
data = {}
else:
data = json.load(f)
data.update({player_name: {"balance": balance, "portfolio": {}}})
with open(player_data_file, 'w') as f:
json.dump(data, f, indent=4)
Related
I'm trying to save data with Python and Json, Im trying to have it save like this
"UserID" {
"Code":12123
}
But I cannot get anywhere near this look or working order. Here is the code that is saving to the Json.
with open('data.json') as f:
data = json.load(f)
data.append([str(ctx.author.id)]["Code"])
with open('data.json','w') as f:
json.dump(data, f)
How can I get it to save like my example above so I can be able to get the code via the userid when fetching the codes.
#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
I am looking for some assistance with writing API results to a .CSV file using Python.
I have my source as CSV file. It contains the below urls in a column as separate rows.
https://webapi.nhtsa.gov/api/SafetyRatings/modelyear/2013/make/Acura/model/rdx?format=csv
https://webapi.nhtsa.gov/api/SafetyRatings/modelyear/2017/make/Chevrolet/model/Corvette?format=csv
I can call the Web API and get the printed results. Please find attached 'Web API results' snapshot.
When I try to export these results into a csv, I am getting them as per the attached 'API results csv'. It is not transferring all the records. Right now, It is only sending the last record to csv.
My final output should be as per the attached 'My final output should be' for all the given inputs.
Please find the below python code that I have used. I appreciate your help on this. Please find attached image for my code.My Code
import csv, requests
with open('C:/Desktop/iva.csv',newline ='') as f:
reader = csv.reader(f)
for row in reader:
urls = row[0]
print(urls)
r = requests.get(urls)
print (r.text)
with open('C:/Desktop/ivan.csv', 'w') as csvfile:
csvfile.write(r.text)
You'll have to create a writer object of the csvfile(to be created). and use the writerow() method you could write to the csvfile.
import csv,requests
with open('C:/Desktop/iva.csv',newline ='') as f:
reader = csv.reader(f)
for row in reader:
urls = row[0]
print(urls)
r = requests.get(urls)
print (r.text)
with open('C:/Desktop/ivan.csv', 'w') as csvfile:
writerobj=csv.writer(r.text)
for line in reader:
writerobj.writerow(line)
One problem in your code is that every time you open a file using open and mode w, any existing content in that file will be lost. You could prevent that by using append mode open(filename, 'a') instead.
But even better. Just open the output file once, outside the for loop.
import csv, requests
with open('iva.csv') as infile, open('ivan.csv', 'w') as outfile:
reader = csv.reader(infile)
for row in reader:
r = requests.get(urls[0])
outfile.write(r.text)
This is my current code:
def ftp_upload(local_ftpfile_path, ftp_ftpfile_path):
json_data = {...}
with open(local_ftpfile_path, 'w') as f:
json.dump(json_data, f)
f.close()
file = open(local_ftpfile_path, 'rb') # file to send
try:
session.storbinary('STOR ' + ftp_ftpfile_path, file) # send the file
except ... :
...
else:
...
Everything works, but I think it's a little stupid to open two files.
How can I convert it to just one file, so either just to f or to file, but not both.
How would you have to change the w and the rb?
Thanks for the help!
best regards,
Lukas
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: