problem with join

Gabriel Genellina gagsl-py2 at
Fri Mar 7 16:46:06 CET 2008

En Fri, 07 Mar 2008 13:12:13 -0200, nodrogbrown <nodrogbrown at>  

> i am using python on WinXP..i have a string 'folder ' that i want to
> join to a set of imagefile names to create complete qualified names so
> that i can create objects out of them
> folder='F:/brown/code/python/fgrp1'
> filenms=['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
> filenameslist=[]
> for x in filenms:
> 	myfile=join(folder,x)
> 	filenameslist.append(myfile)
> now when i print the filenameslist  i find that it looks like
> ['F:/brown/code/python/fgrp1\\amber1.jpg',
> 'F:/brown/code/python/fgrp1\\amber3.jpg', 'F:/brown/code/python/fgrp1\
> \amy1.jpg', 'F:/brown/code/python/fgrp1\\amy2.jpg']
> is there some problem with the way i use join? why do i get \\ infront
> of  the basename?

join is fine. "\\" is a single character. \ is used as the escape  
character, and has to be doubled when representing itself. Print an  
individual element to see the effect:

print filenameslist[0]

(a list uses repr() on its elements instead of str()).

> i would prefer it like 'F:/brown/code/python/fgrp1/basename.jpg',

If the string is only used to open a file, and never shown to the user,  
what you prefer is irrelevant, isn't it?
What is important here is what Windows prefers, and that's a backslash,  
although many times / is accepted too. You can convert the file names to  
their preferred spelling using os.path.normpath

Back to your code, try this:

 from os.path import join, normpath
folder = 'F:/brown/code/python/fgrp1'
names = ['amber1.jpg', 'amber3.jpg', 'amy1.jpg', 'amy2.jpg']
filenameslist = [normpath(join(folder, name)) for name in names]

Gabriel Genellina

More information about the Python-list mailing list