Python: saving screenshot in loop

0

Why does the code below save the file one above the other?

I want each screenshot to generate 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.
    
asked by anonymous 09.05.2018 / 03:29

1 answer

2

Because the file name is only set once, when the code is started. Thus, all screenshots will have the same name and therefore will overwrite the previous file. To avoid this, you need to update the filename according to the time by putting the definition of the file 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)
    
09.05.2018 / 03:35