Phyton: FileNotFoundError / No such file or directory

Hello,

i’m working with Discord.py and did a quiz bot with embed messages.

After random times I get this error message:

[2022-11-01 04:19:14] [ERROR ] discord.client: Ignoring exception in on_message Traceback (most recent call last): File “C:\Users\XXX\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py”, line 409, in _run_event await coro(*args, **kwargs) File "C:\Users\XXX\Desktop\DC-BOT\Discord-Bot\main.py, line 286, in on_message fullChar = discord.File(hintCharPath, filename=“image.png”) File “C:\Users\XXX\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\file.py”, line 97, in init self.fp = open(fp, ‘rb’) FileNotFoundError: [Errno 2] No such file or directory: ‘XXX/YYY ZZZ.jpg’

That’s the part of the code:

embed = discord.Embed(title=helpTitle, description=helpDesc, color=helpColor)
FixPath = helpChar.replace('\u200b', '')
hintCharPath = "XXX/" + FixPath + '.jpg'
fullChar = discord.File(hintCharPath, filename="image.png")
embed.set_author(name="XXX", icon_url="URL")
embed.set_image(url="attachment://image.png")
await message.channel.send(file=fullChar, embed=embedLeague)

(In case anyone is wondering: I have renamed some data like the path name)The path is correct and so is the naming. It happens from time to time about every 10th time to random images that normaly work.

Someone said I could try to parse the full file path. So the one I get with os.getcwd(). But that didn’t work either.

Does anyone know what to do?

Could it be as simple as the path separator: “/” in your code and in the error message, “\” as far as Windows is concerned?

os.path.join is the traditional solution for this, or the newer pathlib would be worth a look.

Use the following code to join the path parts and create an absolute path:

import os
hintCharPath = os.path.abspath(os.path.join("XXX", FixPath + ".jpg"))

Print out the values in helpChar, FixPath, hintCharPath. List all
the files in the folder hintCharPath and/or the XXX folder. Print
out the result of a call to os.getcwd() to see where your code is
standing when it executes.

You compute FixPath by discarding all instances of the character
\u200b. Is that correct?

It’s complaining that the file path does not exist. Clearly either the
path is wrong, you’re standing in the wrong place to use a relative path
or your code should have a plan to cope with a missing file, if that is
a thing that may normally happen.

Cheers,
Cameron Simpson cs@cskk.id.au

Seriously, try using pathlib.Path, it will greatly help.

hintCharPath = (Path("XXX") / FixPath).with_suffix(".jpg")

Not sure if discord.File accepts Path, if not, just use str()