[Tutor] Making Incremental Filenames

John Fouhy john at fouhy.net
Wed Jul 11 08:07:36 CEST 2007

On 11/07/07, Brian Hicks <therealcaffeine at gmail.com> wrote:
>  Hi, I'm making a webcam automation script (for a project 365 photo thing)
> and I can't figure out how to increment the filename every time the script
> saves an image.  I'm using this snippet of code to count the tiles in the
> directory:
>  This returns 4 in my case.  I tried using os.path.join to join
> "C:\Users\Username\Pictures\365\day",filecount (which is
> 4),".jpg" so I can save it using the webcam library I have, but that throws
> a rather serious looking error, which is like this:

os.path.join is unlikely to be what you want.  You use os.path.join to
join separate chunks of path together, where each bit is complete on
its own.  For example, os.path.join("C:\Foo", "bar") would produce
"C:\Foo\bar" (note the backslash between Foo and bar).  The goal is to
provide a platform-independent way of joining pathnames together, so
you don't have to figure out whether to use '/' or '\' or something

You need string formatting -- the % operator.  Try this:

filename = "C:\\Users\\Username\\Pictures\\365\\day%d.jpg" % filecount

Or even:

filename = "C:\\Users\\Username\\Pictures\\365\\day%3d.jpg" % filecount
(this will give you 001, 002, ...)

Check the python docs (library reference, under "Sequence types") for
more information.


More information about the Tutor mailing list