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

Luke Paireepinart rabidpoobear at gmail.com
Sun Feb 21 01:30:53 CET 2010


On Sat, Feb 20, 2010 at 6:11 PM, Dayo Adewunmi <contactdayo at gmail.com>wrote:

> Shashwat Anand wrote:
>
>>
>> <snip>
>>
>>
>>      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)
>>
>>
>> I see a small typo here.
>> print "<a href=\"%s/%s\"><img src=\"%s\%s\" /></a>"
>> %(currentdir,filename,currentdir,filename)  should rather be print "<a
>> href=\"%s/%s\"><img src=\"%s/%s\" /></a>"
>> %(currentdir,filename,currentdir,filename) ..
>> notice the slashes "%s/%s" in href tag and "%s\%s" in img tag.
>>
>> >>> filename = '1.jpg'
>> >>> absolutePath = os.getcwd()
>> >>> currentdir = os.path.basename(absolutePath)
>> >>> print "<a href=\"%s/%s\"><img src=\"%s/%s\" /></a>"
>> %(currentdir,filename,currentdir,filename)
>> <a href="Desktop/1.jpg"><img src="Desktop/1.jpg" /></a>
>>
>>
>> ~l0nwlf
>>
> Arrrgh. Didn't see that forwardslash I put in there. It's fixed and works
> now.
> Thanks!
>
>
> If you're using OS functions you should NOT bank on the slashes being
forward-slashes.  This is platform-specific behavior.  You should use
os.path.split() to get the elements of your path and do a "/".join() on
them.  Otherwise your code will break on Windows because the path will be
denoted with backslashes.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100220/6d5c96d3/attachment.html>


More information about the Tutor mailing list