在 Mac 和 Windows 中运行时,Python path.join 行为不同

问题描述

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

在windows命令提示符输出是

usersscriptspythonsample

在MAC终端输出是

users/scripts/pythonsample

另外,当我运行以下代码时

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

在windows命令提示符输出是

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

在MAC终端输出是

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

所以在多个平台上解析和获取没有完整路径的文件名变得很困难.

我可以编写一个 if else 块来决定脚本是在 Windows 还是 MAC 或 CGYWIN 中运行.

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)

但是有没有一种简单的方法可以在没有 if else 阻塞的情况下完成此操作?

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


解决方案

这正是您应该期待的.在 Windows 上,os.path 为您提供 Windows 风格的路径;在 Mac OS X 上,它为您提供 POSIX 样式的路径.

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.

如果您希望保证 POSIX 路径的所有内容,请不要使用 os.path,而是使用 posixpath.

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

另一方面,如果您的路径即使在 Windows 上也可能是 POSIX 格式(因为 Windows 的大多数部分都处理 POSIX 样式的路径,并且许多工具会生成 POSIX 样式的路径)并且希望保证您有一个本地路径,调用 os.path.normpath.

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.

相关文章