Fix Python – Python, add trailing slash to directory string, os independently

Question

Asked By – ohho

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

Now we will see solution for issue: Python, add trailing slash to directory string, os independently


Answer

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.

This question is answered By – Steven T. Snyder

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0