0

So I'm trying to save a screenshot with the same name for example, "Screen" and then if it already exists, save as "Screen1" and "Screen2" and so on.

This is my code:

driver.get_screenshot_as_file("Screen.png")
Cassano
  • 253
  • 5
  • 36
  • 1
    This post may help: https://stackoverflow.com/questions/13852700/create-file-but-if-name-exists-add-number Basically, check if the file you are trying to create already exists, if it does increment the filename. Or use the `tempfile` functionality builtin to python to generate unique names. – abc Dec 20 '21 at 21:14
  • 1
    The much better way to do this would be to put a date/time stamp in the file name. That way you won't get any name collisions. – JeffC Dec 20 '21 at 22:17

1 Answers1

1

Here you can find more information about it. You could use a while loop and check for every name (Screen1, Screen2, ...), whether it exists or not. A short example:

import os.path

i = 1
while True:
    fname = "Screen" + str(i) + ".png"
    if not os.path.isfile(fname):
        break
    i += 1
print(fname)

You could also store the current i and use it when saving a screenshot, this might be more efficient than this approach.

Frederick
  • 450
  • 4
  • 22