Image.save() - FileNotFoundError
Asked Answered
N

1

8

I have a toolbar. It allows you to take screenshots with one button:

def screenshot():
    try:
        os.mkdir(r"C:\Screenshots")
    except FileExistsError:
        pass
    
    global img
    img = ImageGrab.grab()
    global today
    today = time.strftime("%d_%B_%Y__%H_%m_%S")
    saveas=os.path.join(SaveDirectory, "Screenshot_" + today + ".jpg")
    img.save(saveas)
    bubble = Thread(target = balloon_tip, args = ("Saved!", "Screenshot was saved at C:\Screenshots"))
    bubble.start()

However I get this error:

    Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python3.6\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Python3.6\lib\threading.py", line 864, in run
        self._target(*self._args, **self._kwargs)
  File "C:\Users\mbilal25tr\Desktop\Python Projects\Toolbar py\toolbar.pyw", line 140, in screenshot
    img.save(saveas)
      File "C:\Python3.6\lib\site-packages\PIL\Image.py", line 1725, in save
    fp = builtins.open(filename, "w+b")
    FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Screenshot\\Screenshot_29_March_2017__19_03_01.jpg'

But I don't get it! Isn't img.save() supposed to create an image file? Why does it try to open it before creating? How should I expect it to find it and run without an error?

I'm using Python 3.

Negligent answered 29/3, 2017 at 17:39 Comment(6)
Hey I think I found it! The path is actually C:\Screeshots but in error it is C:\Screenshot. an s is missing but why? I don't know any escaping as s\ !Negligent
It's not missing the file ... it's missing the directory. Your code to create the directory uses a different directory name than your save img ('s' on the end).Eparch
@Jonathan yes but why does that 's' dissapear?Negligent
OP is using a variable 'SaveDirectory' for building the path and it obviously does not match the literal they used to make the directory. Coding correctly and using the variable in both places would have avoided this problem.Eparch
@Jonathan I think I found it. SaveDirectory is readed from a text file. I've done lineoftext[:-1] because of \n escaping. But I forget that SaveDirectory is the last line and I didn't press enter after writing it. I will try it tomorrow.Negligent
I see. Use lineoftext.strip() instead, which removes newlines (and other whitespace) only if it's there.Eparch
F
1

I think something is wrong with your SaveDirectory variable, not at the save function. As I see from the error, the SaveDirectory variable's value is C:\\Screenshot\\
and the directory you want to save that img in is C:\\Screenshots\\

and under

That's why your program didn't find the folder that you want to save in, because "Screenshot" and "Screenshots" are two completely different name with the computer.
All you need to do is fix the SaveDirectory variable.

Frequency answered 9/6, 2023 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.