在Mac和Windows中运行时,Python path.join行为不同 [英] Python path.join behavior is different when run in Mac vs Windows

查看:265
本文介绍了在Mac和Windows中运行时,Python path.join行为不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在Windows命令提示符下输出的是

users\scripts\pythonsample

在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)

但是有一个简单的方法来完成此操作,而没有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行为不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆