1
Chase2E 2019-12-02 13:44:24 +08:00
同问
|
2
itskingname 2019-12-02 13:45:26 +08:00
那么你就不要用 os.path.join,改成
``` path = ['/abc/def', 'mnk'] result = '/'.join(path) print(result) ``` |
3
wangyzj 2019-12-02 13:46:34 +08:00
别用 os.path
|
4
XIVN1987 OP |
5
wuwukai007 2019-12-02 13:50:33 +08:00 via Android
os.path.join(abc,def,mnk)
|
6
littleylv 2019-12-02 13:55:04 +08:00
你本来就不应该把 /abc/def 写死,代码里写死路径分隔符是不好的习惯
不知道 python 有没有定义常量,PHP 有一个 DIRECTORY_SEPARATOR https://www.php.net/manual/en/dir.constants.php |
7
hhhsuan 2019-12-02 13:55:55 +08:00 1
用 pathlib
|
9
Trim21 2019-12-02 13:57:45 +08:00 via Android
手头没电脑,没法实际测试。你看看 urllib 里面的 join 行不行
|
10
ClericPy 2019-12-02 13:59:50 +08:00
pathlib 的 Path 对象有个 as_posix 就可以了, 何必非纠结 os.path 呢
|
11
Cooky 2019-12-02 14:00:36 +08:00 via Android 1
pathlib ?
|
12
hhhsuan 2019-12-02 14:00:56 +08:00 2
from pathlib import PurePosixPath
p = PurePosixPath("/abc/def") p = p.joinpath("mnk") print(p) > /abc/def/mnk |
13
Procumbens 2019-12-02 14:09:04 +08:00 3
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 |
14
XIVN1987 OP |
15
XIVN1987 OP 感觉 @Procumbens 提出的方法最简洁
只需要 import posixpath as path 然后把 os.path.join('/abc/def', 'mnk') 都替换成 path.join('abc/def', 'mnk') 就可以了,, |
16
yuankui 2019-12-02 14:23:51 +08:00
os.path 不就是为了做跨平台兼容的吗? window 用 /路径分隔符有啥意义?
|
17
yucongo 2019-12-02 14:33:29 +08:00
from pathlib import Path
Path('/abc/def', 'mnk').as_posix() # ->'/abc/def/mnk' |
19
starix 2019-12-02 15:26:36 +08:00
os.sep
|
20
BlueSummer8 2019-12-02 15:31:11 +08:00
用 str 的 join 怎样,'/'.join(('aaa', 'bbb'))
|
21
JCZ2MkKb5S8ZX9pq 2019-12-02 15:46:29 +08:00
我发到远程主机的,所以碰到过类似问题。
可以考虑自己写一个 path_join 方法,这样里面套什么模块或逻辑都行,以后改起来也方便点只改一处。 我是写了一个 format_path,比如有些情况第一个斜杠也需要处理,等等。然后把 replace 啥的都塞里面了。 |