在python中,我有变量base_dir
和filename
。我想将它们连接起来以获得fullpath
。但是在Windows下,我应该使用\
和用于POSIX /
。
fullpath = "%s/%s" % ( base_dir, filename ) # for Linux
如何使该平台独立?
Answers:
您要为此使用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'
base_dir
(尽管OP使用它)
abspath()
如果其中有任何亲戚,添加呼叫应使其成为完整路径。
在这里挖掘一个老问题,但是在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()
是更简单的方法。
我为此做了一个辅助类:
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
谢谢你 对于使用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)