1

I am trying to save my images with the time epoch plus iterating integers like this:

text_img.save('/content/result/' + epoch + '_%03d' + '.png' , format="png")

However, the output is something like this:

16087965_%03d.jpg

The formatting does not work for some reason. I do not know why.

2
  • What is _%03d supposed to give? Commented Dec 23, 2020 at 12:14
  • _001, _002, and so on Commented Dec 23, 2020 at 12:15

1 Answer 1

1

At the moment, '_%03d' is just a literal string. Since your code is in a loop, you'll want to provide the loop counter variable to be formatted.

Try something like:

import time

for i in range(100):
    epoch = str(int(time.time() / 1000))
    name = '/content/result/' + epoch + '_%03d' % i + '.png'
    text_img.save(name, format='png')

Or you can instead achieve the same thing using f-strings:

import time

for i in range(100):
    epoch = str(int(time.time() / 1000))
    name = f'/content/result/{epoch}_{i:03}.png'
    text_img.save(name, format='png')
Sign up to request clarification or add additional context in comments.

4 Comments

Also, be aware that you can probably move the assignment to epoch before the loop. I assume the point of the increasing integers is to distinguish files sharing the same timestamp.
I'm not using the loop anymore. I just want to be able to use this format without it being a literal string..
Yep, @chepner makes sense. The question didn't provide a lot context so I just put it in the body initially, but I suppose that was the OP's intention.
@oo92 You need some variable (or value). %03d doesn't generate an integer itself, it only provides the "instruction" to the % operator for how to format an integer you provide. That is, %03d isn't special to the string, only to the % operator which parses the string in order to produce a new string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.