Python path.join behavior is different when run in

2020-04-22 02:19发布

问题:

I want my Project, built in PYTHON to support Windows Linux MAC in any terminal(MAC, CYGWIN, Windows etc). I can able to achieve but I am facing some issue When I run the following

import os
mypath = os.path.join('users','scripts', 'pythonsample')
print mypath

In windows command prompt output is

users\scripts\pythonsample

In MAC terminal output is

users/scripts/pythonsample

Also, when I run the following code

import glob
glob.glob(os.path.join('users','scripts', 'pythonsample','*.*'))

In windows command prompt output is

[users/scripts\\pythonsample\\a1.py,
users/scripts\\pythonsample\\a2.py,
users/scripts\\pythonsample\\a3.py
users/scripts\\pythonsample\\a4.py]

In MAC terminal output is

[users/scripts/pythonsample/a1.py,
users/scripts/pythonsample/a2.py,
users/scripts/pythonsample/a3.py
users/scripts/pythonsample/a4.py]

So to parse and get get the name of the file without whole path becomes difficult in multiple platforms.

I can write a if else block to decide whether the script is running in Windows or MAC or CGYWIN.

import sys
#Output of below command is Win32, linux2, darwin, cgywin 
print(sys.platform)

but is there a easy way to accomplish this with out if else block?

回答1:

This is exactly what you should expect. On Windows, os.path gives you Windows-style paths; on Mac OS X, it gives you POSIX-style paths.

If you're looking to guarantee POSIX paths everything, don't use os.path at all, use posixpath instead.

On the other hand, if you've got paths that may be in POSIX format even on Windows (since most parts of Windows handle POSIX-style paths, and many tools generate POSIX-style paths) and want to guarantee that you've got a native path, call os.path.normpath.