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.
Related
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)
I need to save a file which was sent to telegram bot.
import telebot
bot = "Here is my token"
#bot.message_handler(content_types='') #IDK what content type I need to use to receive every file
def addfile(message):
#Here I need to save file which was sent
That would look something like this:
#bot.message_handler(content_types=['document', 'photo', 'audio', 'video', 'voice']) # list relevant content types
def addfile(message):
file_name = message.document.file_name
file_info = bot.get_file(message.document.file_id)
downloaded_file = bot.download_file(file_info.file_path)
with open(file_name, 'wb') as new_file:
new_file.write(downloaded_file)
#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
https://fastapi.tiangolo.com/tutorial/request-files/
*Solved Below *
I've gotten an appropriately sized array of bytes and I'm not sure how to parse it correctly to save received form file data.
Almost working:
#app.post("/uploadfiles/")
async def create_files(files: List[bytes] = File(...)):
out_file = open("files/1.txt", "w") # open for [w]riting as [b]inary
out_file.write( str([(file) for file in files]))
out_file.close()
return {"file_sizes": [len(file) for file in files]}
The script results in a file that is no longer a readable .png. I assume I'm using the libraries incorrectly but I'm not sure which to start with: HTMLResponse, FastAPI, multipart or List maybe? Any ideas or docs on how to properly parse these bytes back together again?
Edit
Per a break and once over review of the FastAPI docs, I spotted that this particular array of byte data is multipart/form-data data (so maybe I'll find a python library for reading form data/images):
Here is a small example (first ~100chars) of the data that is generated:
[b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x03\xe8\x00\x00\x01\xf4\x08\x06\x00\x00\x00\xae(\x07-\x00\x00\x01\x86iCCPICC profile\x00\x00(\x91}\x91=H\
I did it!!!
The secret was pythons native byte recognition libraries and order of ops!!
#app.post("/uploadfiles/")
async def create_files(files: bytes = File(...)):
out_file = open("files/1.jpg", "wb") # open for [w]riting as [b]inary
out_file.write( bytes([(file) for file in files]))
out_file.close()
Still work to do on the file naming system :) GL Everyone!
Edit 2
Since the below answer didn't function, I scripted a file name appender:
#app.post("/uploadfiles/")
async def create_files(files: bytes = File(...)):
with open('C:/data/sample.txt', 'r', encoding='utf-8') as g:
data=g.readlines()
for line in data:
counter = int(line)
with open('C:/data/sample.txt', 'w') as f:
counter = counter + 1
f.write(str(counter))
out_file = open("files/" + str(counter) + ".jpg", "wb") # open for [w]riting as [b]inary
out_file.write( bytes([(file) for file in files]))
out_file.close()
Thanks for the help everyone! Happy hacking :^)
Edit 3
I've been informed that the method of which I am posting could be incorrect practice in conjunction with FastAPI so to better understand this I am posting the relevant javascript that posts to the backend:
Here is the relevant code from my reactjs form post script:
onSubmit = (e) => {
e.preventDefault();
const formData = new FormData();
if (this.state.images != null) {
var form = document.getElementById("apiupform");
document.getElementById("apiupform").hidden = true;
Array.from(this.state.images).forEach((image) => {
formData.append("files", image);
});
axios
.post(`https://****.com/uploadfiles/`, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
Thank you everyone for the help with this work. I will update it as I find improvements :)
You can save the uploaded files this way,
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
#app.post("/upload-file/")
async def create_upload_file(uploaded_file: UploadFile = File(...)):
file_location = f"files/{uploaded_file.filename}"
with open(file_location, "wb+") as file_object:
file_object.write(uploaded_file.file.read())
return {"info": f"file '{uploaded_file.filename}' saved at '{file_location}'"}
OR,
maybe a more efficient way using the shutil.copyfileobj(...) method as,
import shutil
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
#app.post("/upload-file/")
async def create_upload_file(uploaded_file: UploadFile = File(...)):
file_location = f"files/{uploaded_file.filename}"
with open(file_location, "wb+") as file_object:
shutil.copyfileobj(uploaded_file.file, file_object)
return {"info": f"file '{uploaded_file.filename}' saved at '{file_location}'"}
Sample Swagger
I would use an asynchronous library like aiofiles for file operations.
Since you are running your app inside an event loop the file writing operation will block the entire execution of your app.
import aiofiles
#app.post("/uploadfiles/")
async def create_files(files: bytes = File(...)):
async with aiofiles.open("files/1.jpg", "wb") as f:
await f.write(bytes([(file) for file in files]))
this is what worked for me..
#app.post("/fileUpload/")
def fileUpload(ufile: UploadFile = File(...)):
s = str(ufile.file.read(), 'utf-8')
with open(ufile.filename, "w+") as buffer:
buffer.write(s)
I have searched all through Stackoverflow and I can't find a fix, Granted a lot of other people have the same error they didn't really help when I looked them up. The error is:
CommandInvokeError: Command raised an exception: UnpicklingError: invalid load key, 'H'
Here is the code I have at the moment:
#bot.command(pass_context=True)
async def joke(ctx):
with open("joke_file1.pk1", "rb") as f:
joke_list = pickle.load(f)
await bot.say(random.choice(joke_list))
#bot.command(pass_context=True)
async def addjoke(ctx, *args):
if not os.path.isfile("joke_file1.pk1"):
joke_list = []
else:
with open("joke_file1.pk1", "rb") as f:
joke_list = pickle.load(f)
joke_list.append(" ".join(args))
with open("joke_file1.pk1", "wb") as f:
pickle.dump(joke_list, f)
That is in my main file and I also have another file for letting it read from the .txt file I have and heres the code for that one
import pickle
with open("joke_file1.pk1", "rb") as f:
jokes = pickle.load(f)
with open("joke_title1.txt", "r") as f:
data = f.readlines()
for joke in data:
jokes.append(joke.replace("\n", ""))
with open("joke_file1.pk1", "wb") as f:
pickle.dump(jokes, f)
I get the same error on that second file as the top one. If someone can help me fix this I thank you!
This image is what all the files look like. Cow.py is the code that reads the .txt file
I fixed everything. All I needed to do is remove the preset files and run the bot again. Once ran everything worked again. T