gpt4 book ai didi

python - 如何用斜线分割路径?

转载 作者:行者123 更新时间:2023-11-28 19:49:11 24 4
gpt4 key购买 nike

我需要在我的应用程序中添加和拆分路径。我想在 Windows 和 Linux 上使用这个应用程序。这是我添加路径的代码

 path = os.path.join(dir0,dir1,dir2,fn)

但是当我用斜线分割时,我遇到了问题。因为

windows 中的路径如下:

dir0\dir1\dir2\fn

linux下的路径

dir0/dir1/dir2/fn

现在我如何用单个代码拆分路径(在使用其他平台/平台独立时不更改代码)

最佳答案

你可以使用os.sep

只是

import os
path_string.split(os.sep)

有关更多信息,请查看 doc

os.path.join(path1[, path2[, ...]]) Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) following each non-empty part except the last. (This means that an empty last part will result in a path that ends with a separator.) Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

关于python - 如何用斜线分割路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22804002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com