Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Platform independent path concatenation using "/" , "\"?

Tags:

python

path

In python I have variables base_dir and filename. I would like to concatenate them to obtain fullpath. But under windows I should use \ and for POSIX / .

fullpath = "%s/%s" % ( base_dir, filename ) # for Linux 

How can I make this platform independent?

like image 781
Jakub M. Avatar asked Jun 06 '12 16:06

Jakub M.


People also ask

How do you concatenate a path 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.

Which is the correct constant for a platform independent directory separator in Python?

In Windows you can use either \ or / as a directory separator.

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.


2 Answers

You want to use os.path.join() for this.

The strength of using this rather than string concatenation etc is that it is aware of the various OS specific issues, such as path separators. Examples:

import os 

Under Windows 7:

base_dir = r'c:\bla\bing' filename = r'data.txt'  os.path.join(base_dir, filename) 'c:\\bla\\bing\\data.txt' 

Under Linux:

base_dir = '/bla/bing' filename = 'data.txt'  os.path.join(base_dir, filename) '/bla/bing/data.txt' 

The os module contains many useful methods for directory, path manipulation and finding out OS specific information, such as the separator used in paths via os.sep

like image 127
Levon Avatar answered Sep 16 '22 14:09

Levon


Use os.path.join():

import os fullpath = os.path.join(base_dir, filename) 

The os.path module contains all of the methods you should need for platform independent path manipulation, but in case you need to know what the path separator is on the current platform you can use os.sep.

like image 25
Andrew Clark Avatar answered Sep 18 '22 14:09

Andrew Clark