Elegant way to take basename of directory in Python?

user248237 picture user248237 · Apr 18, 2010 · Viewed 8.9k times · Source

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.

Answer

John Machin picture John Machin · Apr 18, 2010

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

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