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 行为不同
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何将一个类的函数分成多个文件? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 沿轴计算直方图 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
