使用“ /”,“ \”的平台独立路径连接?


83

在python中,我有变量base_dirfilename。我想将它们连接起来以获得fullpath。但是在Windows下,我应该使用\和用于POSIX /

fullpath = "%s/%s" % ( base_dir, filename ) # for Linux

如何使该平台独立?




Answers:


145

您要为此使用os.path.join()

使用此方法而不是使用字符串连接等方法的优势在于,它知道各种特定于OS的问题,例如路径分隔符。例子:

import os

Windows 7下

base_dir = r'c:\bla\bing'
filename = r'data.txt'

os.path.join(base_dir, filename)
'c:\\bla\\bing\\data.txt'

Linux下

base_dir = '/bla/bing'
filename = 'data.txt'

os.path.join(base_dir, filename)
'/bla/bing/data.txt'

所述OS模块包含目录,路径操纵并找出OS特定信息许多有用的方法,如在经由路径中使用的分离器os.sep


26

用途os.path.join()

import os
fullpath = os.path.join(base_dir, filename)

os.path中模块包含了所有的你应该需要独立于平台的路径操作方法,但如果你需要知道的路径分隔符是当前的平台,你可以使用什么os.sep


1
如果是相对路径,则它不是完整路径base_dir(尽管OP使用它)
jfs 2012年

1
abspath()如果其中有任何亲戚,添加呼叫应使其成为完整路径。
martineau 2012年

@Andrew Clark,os.sep在Windows上返回“ \\”,但是即使我使用“ /”,它仍然可以工作。如果仅使用“ /”,有什么问题吗?
multigoodverse

12

在这里挖掘一个老问题,但是在Python 3.4+上,您可以使用pathlib运算符

from pathlib import Path

# evaluates to ./src/cool-code/coolest-code.py on Mac
concatenated_path = Path("./src") / "cool-code\\coolest-code.py"

os.path.join()您有幸运行最新版本的Python时,它可能更具可读性。但是,如果必须在严格或遗留的环境中运行代码,则还需要权衡与旧版Python的兼容性。


我非常喜欢pathlib。但是,在Python2安装中通常默认情况下未安装它。如果您不希望用户也必须安装pathlib,那os.path.join()是更简单的方法。
Marcel Waldvogel,

7
import os
path = os.path.join("foo", "bar")
path = os.path.join("foo", "bar", "alice", "bob") # More than 2 params allowed.

1

我为此做了一个辅助类:

import os

class u(str):
    """
        Class to deal with urls concat.
    """
    def __init__(self, url):
        self.url = str(url)

    def __add__(self, other):
        if isinstance(other, u):
            return u(os.path.join(self.url, other.url))
        else:
            return u(os.path.join(self.url, other))

    def __unicode__(self):
        return self.url

    def __repr__(self):
        return self.url

用法是:

    a = u("http://some/path")
    b = a + "and/some/another/path" # http://some/path/and/some/another/path

这不会在Windows上插入反斜杠吗?
Marcel Waldvogel,

0

谢谢你 对于使用fbs或pyinstaller和冻结的应用程序看到此错误的其他任何人。

我可以使用现在可以完美使用的以下内容。

target_db = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), "sqlite_example.db")

我在做这种模糊处理,在此之前显然并不理想。

if platform == 'Windows':
    target_db = (os.path.abspath(os.path.dirname(sys.argv[0])) + "\\" + "sqlite_example.db")

if platform == 'Linux' or 'MAC':
    target_db = (os.path.abspath(os.path.dirname(sys.argv[0])) + "/" + "sqlite_example.db")

target_db_path = target_db
print(target_db_path)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.