[Tutor] Making Incremental Filenames
rabidpoobear at gmail.com
Wed Jul 11 08:13:37 CEST 2007
Brian Hicks 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:
> filecount = len(os.walk("C:\Users\Username\Desktop").next())
> 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:
> Traceback (most recent call last):
> File "<pyshell#16>", line 1, in <module>
> filename =
> File "C:\Python25\lib\ntpath.py", line 67, in join
> elif isabs(b):
> File "C:\Python25\lib\ntpath.py", line 53, in isabs
> s = splitdrive(s)
> File "C:\Python25\lib\ntpath.py", line 119, in splitdrive
> if p[1:2] == ':':
> TypeError: 'int' object is unsubscriptable
> I think I need to be looking into converting filecount to a string
> somehow instead of an integer, but once again I'm not sure how and all
> I've tried has given me errors. Please help?
the problem lies in your use of os.path.join.
This joins paths, as the name implies.
will not result in
if you're on Windows.
The purpose of this function in the os module is because directories in
paths are denoted by different characters ('\\' or r'\' on Windoze, '/'
on Unix variants)
so it enables you to use the same path,
on whatever OS you're on without you having to worry about it.
But since you're trying to join a string, an int, and a string together,
the os.path.join function is complaining on the integer.
Even if you converted this to an integer, you wouldn't get the result
In Python, you can perform string concatenation the same way you perform
F.E. 'hello ' + 'world' is the same thing as 'hello world'
so you have a few options...
you can go the + route, but this requires everything to be strings:
'myfilepath/myfilename' + str(file_count) + '.jpg'
or you could go the string substitution route:
'myfilepath/myfilename%s.jpg' % file_count
Note that you could use %i if you are certain it's an integer, but I
usually just use %s for everything (maybe that's bad ;)
Or, as John Fouhy pointed out (I wouldn't have written this e-mail if
I'd received his before starting this one)
you can use the %d.
Also, just a future warning:
If you want to substitute a bunch of things into a string, like
'hello, my name is %s and I like your cat, %s.'
you can't just do
'hello, my name is %s and I like your cat, %s.' % 'john' , 'freckles'
you'd have to do
'hello, my name is %s and I like your cat, %s.' % ('john', 'freckles')
because the substitution expects either a single argument or a tuple
containing all of the values to be substituted.
> -Brian Hicks
> Tutor maillist - Tutor at python.org
More information about the Tutor