Python path.join behavior is different when run in Mac vs Windows(在 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.
这篇关于在 Mac 和 Windows 中运行时,Python path.join 行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Mac 和 Windows 中运行时,Python path.join 行为不同
基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
