Python: loop screenshot saving over

Asked

Viewed 410 times

0

Why the code below saves the file one over the other?

I wish that every screenshot generates a separate file within the specified folder.

import datetime
import pyautogui
import time

#armazena o nome do arquivo no formato dinâmico de ano-mês-dia_hora minuto_segundo, assim: "2018-05-09_224510.png"
nomeArquivo = datetime.datetime.now().strftime('%Y-%M-%d_%H%M%S'+'.png')

#loop para ficar tirando foto da tela de 10 em 10 segudos.
while True:
    foto = pyautogui.screenshot() #faz a foto
    foto.save('C://Users//WJRS//' + nomeArquivo) #salva na pasta indicada.
    time.sleep(10) #atraso de 10 segundos entre uma screenshot e outra.

1 answer

3


Because the file name is only set once, when the code is started. Thus, all screenshots will have the same name and consequently overwrite the previous file. To avoid this, you need to update the file name according to the time by placing the file setting inside the loop:

while True:
    nomeArquivo = datetime.datetime.now().strftime('%Y-%M-%d_%H%M%S'+'.png')
    foto = pyautogui.screenshot()
    foto.save('C://Users//WJRS//' + nomeArquivo)
    time.sleep(10)
  • Poxa vida! Verdade! Muito obrigado Anderson Carlos. I confess that I was exhausted yesterday, after 8 hours of work and 3 more hours of studies I was no longer well... Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.