Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can os.path.join (or other python method) append a '/' automatically for the case of the directory?

Tags:

python

The os.path.join(a, b) method will generate a string ending without '/' no matter it is a file or directory. Now, is there any way (or any other os.path method) to get a '/' automatically for the case of the directory?

like image 521
Hailiang Zhang Avatar asked Jan 24 '12 16:01

Hailiang Zhang


People also ask

What does os path join do 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.

How do you append to a directory in Python?

Answer. Your path (i.e. the list of directories Python goes through to search for modules and files) is stored in the path attribute of the sys module. Since path is a list, you can use the append method to add new directories to the path.

Does os path join add trailing slash?

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

What does os path Join mean?

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.


1 Answers

There is no such function in os.path. It's easy to code up yourself, though:

if os.path.isdir(path):
    path = os.path.join(path, "")

This will add a / if there isn't already one at the end of path in case it points to a directory.

like image 182
Sven Marnach Avatar answered Oct 02 '22 20:10

Sven Marnach