Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, add trailing slash to directory string, os independently

Tags:

python

string

People also ask

How do you make a forward slash in Python?

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash.

What is OS path join?

os. path. join combines path names into one complete path. This means that you can merge multiple parts of a path into one, instead of hard-coding every path name manually.

How do you add two paths in Python?

path. join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator ('/') following each non-empty part except the last path component.

What does OS Sep do?

os. sep. The character used by the operating system to separate pathname components. This is '/' for POSIX and '\\\\' for Windows.


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.


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.