views:

221

answers:

5

I have several scripts that take as input a directory name, and my program creates files in those directories. Sometimes I want to take the basename of a directory given to the program and use it to make various files in the directory. For example,

# directory name given by user via command-line
output_dir = "..." # obtained by OptParser, for example
my_filename = output_dir + '/' + os.path.basename(output_dir) + '.my_program_output'
# write stuff to my_filename

The problem is that if the user gives a directory name with a trailing slash, then os.path.basename will return the empty string, which is not what I want. What is the most elegant way to deal with these slash/trailing slash issues in python? I know I can manually check for the slash at the end of output_dir and remove it if it's there, but there seems like there should be a better way. Is there?

Also, is it OK to manually add '/' characters? E.g. output_dir + '/' os.path.basename() or is there a more generic way to build up paths?

Thanks.

+2  A: 

Manually building up paths is a bad idea for portability; it will break on Windows. You should use os.path.sep.

As for your first question, using os.path.join is the right idea.

Personman
"""it will break on Windows""": Including slashes will break only if you feed it as part of a command to e.g. `os.system()`; the DOS command parser understands only backslashes. Feeding it to e.g. open() is quite OK. However if the constructed path is ever to be displayed to a Windows user or admin, be prepared for a lot of flak :-)
John Machin
+3  A: 

Use os.path.join() to build up paths. For example:

>>> import os.path
>>> path = 'foo/bar'
>>> os.path.join(path, 'filename')
'foo/bar/filename'
>>> path = 'foo/bar/'
>>> os.path.join(path, 'filename')
'foo/bar/filename'
Jeff Bradberry
+1  A: 

to build the paths without writing slashes it is better to use:

os.path.join(dir, subdir, file)

if you want to add separators or get the separator independly of the os, then use

 os.sep
joaquin
as OP stated, the problem is that if d is "mydir" then this would return an empty string.
Ofri Raviv
@Ofri: the corresponding section has been eliminated.
joaquin
+1  A: 

You should use os.path.join() to add paths together.

use

os.path.dirname(os.path.join(output_dir,''))

to extract dirname, while adding a trailing slash if it was omitted.

Ofri Raviv
+4  A: 

To deal with your "trailing slash" issue (and other issues!), sanitise user input with os.path.normpath().

To build paths, use os.path.join()

John Machin