How can I add a trailing slash (/
for *nix, \
for win32) to a directory string, if the tailing slash is not already there? Thanks!
4 Answers
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.
-
4Also adds a slash when
path
happens to be a file rather than a directory. That's slightly inconvenient.– MartinCommented Aug 18, 2019 at 20:28 -
1There seems to be an exception:
print(os.path.join(r'\\server\c',''))
gives\\server\c
(whereasprint(os.path.join(r'\\server\c\x',''))
gives\\server\c\x\
)– omasoudCommented Dec 14, 2020 at 7:00
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)
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
.
-
1Actually, checking
os.path.sep
is not the best approach here, since on windows the path can end both in/
as well as\
.– DanonCommented Feb 16, 2023 at 20:53
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
os.path
module (docs.python.org/library/os.path.html) instead of manipulating strings directly. Useos.path.join
to concatenate path components.os.path.join
and let the standard library figure out the correct path separator.