Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix paths that work for any platform in Python?

Can all paths in a Python program use ".." (for the parent directory) and / (for separating path components), and still work whatever the platform?

On one hand, I have never seen such a claim in the documentation (I may have missed it), and the os and os.path modules do provide facilities for handling paths in a platform agnostic way (os.pardir, os.path.join,…), which lets me think that they are here for a reason.

On the other hand, you can read on StackOverflow that "../path/to/file" works on all platforms…

So, should os.pardir, os.path.join and friends always be used, for portability purposes, or are Unix path names always safe (up to possible character encoding issues)? or maybe "almost always" safe (i.e. working under Windows, OS X, and Linux)?

like image 402
Eric O Lebigot Avatar asked Oct 27 '09 21:10

Eric O Lebigot


People also ask

What are paths in Python?

What is PYTHONPATH? PYTHONPATH is an environment variable which the user can set to add additional directories that the user wants Python to add to the sys. path directory list. In short, we can say that it is an environment variable that you set before running the Python interpreter.

How do you give a directory path in Python?

You can use the os. mkdir("path/to/dir/here") function to create a directory in Python. This function is helpful if you need to create a new directory that doesn't already exist.

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

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


1 Answers

I've never had any problems with using .., although it might be a good idea to convert it to an absolute path using os.path.abspath. Secondly, I would recommend always using os.path.join whereever possible. There are a lot of corner cases (aside from portability issues) in joining paths, and it's good not to have to worry about them. For instance:

>>> '/foo/bar/' + 'qux'
'/foo/bar/qux'
>>> '/foo/bar' + 'qux'
'/foo/barqux'
>>> from os.path import join
>>> join('/foo/bar/', 'qux')
'/foo/bar/qux'
>>> join('/foo/bar', 'qux')
'/foo/bar/qux'

You may run into problems with using .. if you're on some obscure platforms, but I can't name any (Windows, *nix, and OS X all support that notation).

like image 111
Jason Baker Avatar answered Sep 30 '22 12:09

Jason Baker