怎么让 os.path.join 在 windows 下使用'/'而不是'\\'?

2019-12-02 13:41:47 +08:00
 XIVN1987
windows 系统下执行:os.path.join('/abc/def', 'mnk')

结果是:'/abc/def\\mnk'

我想要的结果是:'/abc/def/mnk'

请问如何操作?
5438 次点击
所在节点    Python
21 条回复
Chase2E
2019-12-02 13:44:24 +08:00
同问
itskingname
2019-12-02 13:45:26 +08:00
那么你就不要用 os.path.join,改成

```
path = ['/abc/def', 'mnk']
result = '/'.join(path)
print(result)
```
wangyzj
2019-12-02 13:46:34 +08:00
别用 os.path
XIVN1987
2019-12-02 13:48:03 +08:00
@itskingname

多谢,,麻烦的方式有很多,,比如 os.path.join('/abc/def', 'mnk').replace('\\', '/')

提问是想看看有没有简单的方法
wuwukai007
2019-12-02 13:50:33 +08:00
os.path.join(abc,def,mnk)
littleylv
2019-12-02 13:55:04 +08:00
你本来就不应该把 /abc/def 写死,代码里写死路径分隔符是不好的习惯
不知道 python 有没有定义常量,PHP 有一个 DIRECTORY_SEPARATOR https://www.php.net/manual/en/dir.constants.php
hhhsuan
2019-12-02 13:55:55 +08:00
用 pathlib
Trim21
2019-12-02 13:56:44 +08:00
@littleylv 好像是 os.sep 还是 os.path.sep 来着
Trim21
2019-12-02 13:57:45 +08:00
手头没电脑,没法实际测试。你看看 urllib 里面的 join 行不行
ClericPy
2019-12-02 13:59:50 +08:00
pathlib 的 Path 对象有个 as_posix 就可以了, 何必非纠结 os.path 呢
Cooky
2019-12-02 14:00:36 +08:00
pathlib ?
hhhsuan
2019-12-02 14:00:56 +08:00
from pathlib import PurePosixPath

p = PurePosixPath("/abc/def")
p = p.joinpath("mnk")
print(p)

> /abc/def/mnk
Procumbens
2019-12-02 14:09:04 +08:00
import posixpath
posixpath.join()

From [os.path documentation]( https://docs.python.org/3/library/os.path.html):
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 paths
- ntpath for Windows paths
XIVN1987
2019-12-02 14:11:35 +08:00
@Procumbens

感谢,,感觉这个方法最好
XIVN1987
2019-12-02 14:15:34 +08:00
感觉 @Procumbens 提出的方法最简洁

只需要 import posixpath as path

然后把 os.path.join('/abc/def', 'mnk') 都替换成 path.join('abc/def', 'mnk') 就可以了,,
yuankui
2019-12-02 14:23:51 +08:00
os.path 不就是为了做跨平台兼容的吗? window 用 /路径分隔符有啥意义?
yucongo
2019-12-02 14:33:29 +08:00
from pathlib import Path

Path('/abc/def', 'mnk').as_posix() # ->'/abc/def/mnk'
XIVN1987
2019-12-02 14:35:56 +08:00
@yuankui

如果合成的路径是要发到远程主机上使用的话就有意义了
starix
2019-12-02 15:26:36 +08:00
os.sep
BlueSummer8
2019-12-02 15:31:11 +08:00
用 str 的 join 怎样,'/'.join(('aaa', 'bbb'))

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/625052

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX