0

Recent i was learning pathnames manipulation in python, having a basic understanding of modules the following statements confused me

os and os.path are both modules :( how is this possible

Then i looked at os.py source code and found the following enlightening line of code

57. import posixpath as path

My question are

Why should i use os.path.join('bin','utils') instead of posixpath.join('bin','utils') ?

What is the simples possible way to exlain x and x.y as both modules and when should i apply this technique?

Emmanuel Mtali
  • 4,383
  • 3
  • 27
  • 53
  • 2
    Relevant: http://stackoverflow.com/questions/2724348/should-i-use-import-os-path-or-import-os- "The `os.path` name is an alias for this module on Posix systems; on other systems (e.g. Mac, Windows), `os.path` provides the same operations in a manner specific to that platform, and is an alias to another module (e.g. macpath, ntpath)" – Chris_Rands Nov 28 '16 at 12:21
  • 1
    If you look at the context of that `import posixpath as path` you will see that it only happens if the script is running on a Posix system. `posixpath` is not intended to be used directly by normal user code, you should let `os` handle those details for you. Otherwise, your script won't work on non-Posix systems. – PM 2Ring Nov 28 '16 at 12:26
  • I posted the answer, thanks to @Chris_Rands and @PM 2Ring for pointing that out. Though someone can still use `posixpath` if knows exactly what he/she is doing otherwse `os.path` is the best choice – Emmanuel Mtali Nov 28 '16 at 15:01

1 Answers1

0

Use os.path.join('bin','utils') instead of posixpath.join('bin','utils')

I discover that using os.path is more robust that using posixpath directly.

os.path offer compatibility with different operating system. Simplified code from os.py

if 'posix' == os.name :
    from posix import *
    import posixpath as path
elif 'nt' == os.name :
    from nt import *
    import ntpath as path
....

As you can see using os.path will ensure you are manipulating path for the current os specifics.

Emmanuel Mtali
  • 4,383
  • 3
  • 27
  • 53