I've got this code snippet
print "tmp = ", tmp
print "dirname = ", os.path.dirname(tmp)
print "tmp sane = ", (os.path.dirname(tmp.replace("\\", "/"))).replace("/", "\\")
that produces this result
tmp = \\aaaa.aaa\aaaaaaaa\aaaaaaaaa\aaaa\aaaa\aaaaa\aaaaaaa\aaaaaaa\aaaa.aaaaaaaa_aaaaaa\aa\aaaaa\aaaaaa\aaa\aaaaaa\aa\aaaaa\aaaaaaa_aaaaaaaaa_aaa\aaaa_aa.aaa
dirname =
tmp sane = \\aaaa.aaa\aaaaaaaa\aaaaaaaaa\aaaa\aaaa\aaaaa\aaaaaaa\aaaaaaa\aaaa.aaaaaaaa_aaaaaa\aa\aaaaa\aaaaaa\aaa\aaaaaa\aa\aaaaa\aaaaaaa_aaaaaaaaa_aaa
Any ideas why "tmp sane" works and the simple dirname doesn't? I couldn't find anything related to the windows network names/backslashes.
You are most likely not running this on Windows. The behaviour is entirely consistent with using the os.path
module on anything but an actual Windows environment.
os.path
adjusts behaviour to match the current platform. On Windows, both forward and backward slashes are supported, but on Linux and Mac only forward slashes are recognized. That's to match the actual convention used on the platform you are running your code on.
If you want to split dirnames from Windows paths on a POSIX OS like Mac OS X or Linux, you'll need to import the ntpath
module; that module is what is really used on Windows but it is available still on other platforms:
import ntpath
result = ntpath.dirname(path)
See the top of the os.path
module documentation :
Note : Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The
os.path
module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:
posixpath
for UNIX-style pathsntpath
for Windows pathsmacpath
for old-style MacOS pathsos2emxpath
for OS/2 EMX paths
Cygwin is considered a POSIX environment, not Windows, in this context.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.