[Tutor] os.path.basename() issue with path slashes

Steven D'Aprano steve at pearwood.info
Sun Feb 21 05:04:57 CET 2010


On Sun, 21 Feb 2010 10:49:19 am Dayo Adewunmi wrote:
> Hi all,
>
> This script I'm working on, should take all the image files in the
> current directory and generate an HTML thumbnails.
>
> import os
> import urllib

You import urllib, but don't appear to use it anywhere.

>
> # Generate thumbnail gallery
> def genThumbs():
>     # Get current directory name
>     absolutePath = os.getcwd()
>     urlprefix = "http://kili.org/~dayo"
>     currentdir = os.path.basename(absolutePath)



>     for dirname, subdirname, filenames in os.walk(absolutePath):
>         for filename in filenames:
>             print "<a href=\"%s/%s\"><img src=\"%s\%s\" /></a>"
> %(currentdir,filename,currentdir,filename)

You don't need to escape quotes, just use the other quote. Instead of:

print "<a href=\"%s/%s\"><img src=\"%s\%s\" /></a>"

use:

print '<a href="%s/%s"><img src="%s\%s" /></a>'

Also, I'm not sure why sometimes you use / as a directory separator and 
sometimes \. I think you're trying to do too much in one line, leading 
to repeated code.

# Untested.
for dirname, subdirname, filenames in os.walk(absolutePath):
    for filename in filenames:
        fullpath = os.path.join(currentdir, filename)
        if os.name == 'nt':
            fullpath.replace('\\', '/')
        print '<a href="%s"><img src="%s" /></a>' % (fullpath, fullpath)


Hope that helps.



-- 
Steven D'Aprano


More information about the Tutor mailing list