Counter in python

Asked

Viewed 12,804 times

1

Well I’m doing a screenshot program but I want it to replace in the file name when saving, the characters "XX" by the print number.
Ex: Screenshotxx.jpg in "XX" I want to put the print number ex: 01, 02 Code used:

import pyscreenshot as ImageGrab

def main():
    image = ImageGrab.grab()

    cont = 1

    for c in cont:

        c =+ 1

        image.save('screenShot' + str(c) + '.jpg', 'jpeg')


if __name__ == '__main__':
    main()

I’m using the python 2.7

2 answers

4

Your code is not very clear. You define a variable cont with the value 1 and then uses a variable c in a loop (without using the range), but increases it within the loop.....?

If you know the number of catches you want, put that number inside the variable cont and do so:

cont = 10

for c in range(cont):

    file = 'screenShot{:05d}.jpg'.format(c)

    print(file)

Result (see working on Ideone):

screenShot00000.jpg
screenShot00001.jpg
screenShot00002.jpg
screenShot00003.jpg
screenShot00004.jpg
screenShot00005.jpg
screenShot00006.jpg
screenShot00007.jpg
screenShot00008.jpg
screenShot00009.jpg

The mask 05d used in the call for format says the number is integer (d), with a size of 5 characters with 0 on the left (05 - use only 5 there will be spaces on the left).

I mean, your final code could look like this:

import pyscreenshot as ImageGrab

def main():
    cont = 10 # Número de capturas

    for c in range(cont):

        # Desnecessário
        # c =+ 1 

        image = ImageGrab.grab()
        image.save('screenShot{:05d}.jpg'.format(c), 'jpeg')


if __name__ == '__main__':
    main()
  • Your answer is extensive, but you are not one of the AP confusions that I noticed here (think ue in a stroke of intuition): I think he intends to plot a sequence of screenshots, - does not make sense? In that case, I’d just put the call through to ImageGrab.grab into the loop, and insert a pause, with time.sleep same. You can put one more example like this?

  • @jsbueno You’re right, it makes more sense grab inside the loop. I will change, thanks for the warning! : ) The pause also makes sense, but as none of us is absolutely sure what the AP really wants, I leave it to him. P.S.: Did you really find my answer extensive? rs

  • 1

    There are things I really don’t understand ... This answer is much better compared to the other

0


You should only access the folder where the Screenshots are being saved, check if there are files in it, if yes, takes the last file after sorting, and extract the XX from the name of that last photo, just add +1 and save the new capture, but if the folder is empty, just consider the value 01, because it will be the first catch.

Browser other questions tagged

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