使用“/”,“”的平台无关路径串联?

在 python 中,我有变量 base_dirfilename。我想连接他们获得 fullpath。但是在窗口下我应该使用 \和 POSIX /

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

我如何使这个平台独立?

132187 次浏览

您需要使用 参与()进行此操作。

The strength of using this rather than string concatenation etc is that it is aware of the various OS specific issues, such as path separators. Examples:

import os

视窗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.sep在路径中使用的分隔符

使用 os.path.join():

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

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

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

我为此创建了一个 helper 类:

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

Digging up an old question here, but on Python 3.4+ you can use Pathlib 运算符:

from pathlib import Path


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

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

Thanks for this. For anyone else who sees this using fbs or pyinstaller and frozen apps.

我可以使用下面的工作完美现在。

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

I was doing this fugliness before which was obviously not ideal.

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)