我在某个文件夹中有 file_css 。我想将 file_inc 的路径包含(通过 css include)到其中。 file_inc可能位于file_css的子文件夹中(直接子文件夹或2-3层);甚至与 file_css 位于同一文件夹中。
如何获取file_inc的相对路径?
示例。
- file_css = "d:\my\my.css"。 file_inc =“d:\my\in\more\inc.css”。我想获取字符串“in\more\inc.css”
- 很高兴也有这种情况:file_css =“d:\my\my.css”。 file_inc =“d:\inc.css”。我想获取字符串“..\inc.css”
最佳答案
使用os.path.relpath
:
>>> os.path.relpath('/foo/bar/baz', '/foo')
'bar/baz'
>>> os.path.sep = '\\' # I need this because i'm not on dos/cpm/vax/nt
>>> os.path.relpath('c:\\foo\\bar\\baz', 'c:\\foo')
'bar/baz'
将其与目录名
组合:
def css_relative_path(html_path, css_path):
return os.path.relpath(css_path, os.path.dirname(html_path))
>>> css_relative_path('/foo/bar/baz.html', '/foo/bar/css/baz.css')
'css/baz.css'
关于python - 获取file1的相对路径(相对于file2的路径,file1在file2的子文件夹中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28089731/