pythonfile-existsos.path

Python - os.path.exists for jpg


I tried to read jpg pictures, but the path was always not found even though the path was correct. So I checked with os.path.exists. The image is called "ralf". And for

os.path.exists("C:\Dokumente\ralf.jpg")

I got the return "false".

But when I renamed the image to "IMG-ralf" and tried:

os.path.exists("C:\Dokumente\IMG-ralf.jpg")

It could find the path and the return was "true".

Does anyone know why renaming the image made a difference?

Can I solve the problem differently? I have like 4000 images where the name is related to a specific label (saved in an excel file with name of the image and label), so I can not just rename all of them, because then I won't know the label anymore. Code


Solution

  • The \ character is the escape character. Escaping D and I should generate a warning in stdout, but escaping r will result in a valid character - the carriage return character (https://en.wikipedia.org/wiki/Carriage_return).

    Using a raw string literal should take care of this:

    os.path.exists(r"C:\Dokumente\ralf.jpg")
    # Here --------^