I'm currently facing an issue. (started trying out python 3 hours ago)
So I tried making this discord bot where if a user sends an image, the bot would save it. My issue was the bot wasn't saving it in a certain folder (idk how also haha) so what I tried was I would copy the said image where it would create a new folder and that new folder is where the copied image would be placed. The original copies of the image would then be deleted, thus only leaving the image files in the folder.
My issue here now is that it's not consistent. It works on the first image input but it won't work if it would be attempted on the second time.
I would like to find a simpler way on being able to save an image file where it would then be directed to a folder rather than being saved in the same place as the python file.
@client.command()
async def save(ctx):
try:
url = ctx.message.attachments[0].url
except IndexError:
print("Error : No attachments")
await ctx.send("No attachments detected")
else:
imageName = str(uuid.uuid4()) '.jpg'
r = requests.get(url, stream=True)
with open(imageName,'wb',) as out_file:
print('Saving image: ' imageName)
shutil.copyfileobj(r.raw, out_file,)
images = [f for f in os.listdir() if '.jpg' in f.lower()]
os.mkdir('Images')
for image in images:
new_path = 'Images/' image
shutil.move(image, new_path)```
CodePudding user response:
You just need to change with open(imageName, 'wb') as out_file:
As it is it will save the image in the folder where the script is running, if you want to save them in the Images folder you just have to change that to with open("Images/" imageName, 'wb') as out_file:
or any other folder.
CodePudding user response:
I think you're not giving a specific path, you can give a specific path using os.join(os.getcwd(),Images)
@client.command()
async def save(ctx):
try:
url = ctx.message.attachments[0].url
except IndexError:
print("Error : No attachments")
await ctx.send("No attachments detected")
else:
imageName = str(uuid.uuid4()) '.jpg'
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(specific_path, 'wb') as f:
f.write(r.content)