Python, add trailing slash to directory string, os independently

PythonString

Python Problem Overview


How can I add a trailing slash (/ for *nix, \ for win32) to a directory string, if the tailing slash is not already there? Thanks!

Python Solutions


Solution 1 - Python

os.path.join(path, '') will add the trailing slash if it's not already there.

You can do os.path.join(path, '', '') or os.path.join(path_with_a_trailing_slash, '') and you will still only get one trailing slash.

Solution 2 - Python

Since you want to connect a directory and a filename, use

os.path.join(directory, filename)

If you want to get rid of .\..\..\blah\ paths, use

os.path.join(os.path.normpath(directory), filename)

Solution 3 - Python

You can do it manually by:

path = ...

import os
if not path.endswith(os.path.sep):
    path += os.path.sep

However, it is usually much cleaner to use os.path.join.

Solution 4 - Python

You could use something like this:

os.path.normcase(path)
    Normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes.

Else you could look for something else on this page

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionohhoView Question on Stackoverflow
Solution 1 - PythonSteven T. SnyderView Answer on Stackoverflow
Solution 2 - PythonTim PietzckerView Answer on Stackoverflow
Solution 3 - PythonMax ShawabkehView Answer on Stackoverflow
Solution 4 - PythonBloeperView Answer on Stackoverflow