简体   繁体   中英

Get relative path of file1 (relative to path of file2, file1 is in subfolder of file2)

I have file_css in some folder. I want to include (via css include) path of file_inc into it. file_inc may be in subfolder of file_css (direct subfolder or 2-3 levels); even be in same folder as file_css.

How to get relative path of file_inc?

Example.

  • file_css = "d:\\my\\my.css". file_inc = "d:\\my\\in\\more\\inc.css". i want to get string "in\\more\\inc.css"
  • good to have also case of this: file_css = "d:\\my\\my.css". file_inc = "d:\\inc.css". i want to get string "..\\inc.css"

Use 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'

Combine it with dirname :

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM