Skip to main content
The 2024 Developer Survey results are live! See the results
update answer to point to python3 documentation and separate out relative_path for a better consistency as the full_path was a variable too
Source Link

A better answer would be to use os.path.relpath:

http://docs.python.org/2/library/os.path.html#os.path.relpathhttp://docs.python.org/3/library/os.path.html#os.path.relpath

>>> import os
>>> full_path = '/book/html/wa/foo/bar/'
>>> printrelative_path = '/book/html'
>>> print(os.path.relpath(full_path, '/book/html'relative_path))
'wa/foo/bar'

A better answer would be to use os.path.relpath:

http://docs.python.org/2/library/os.path.html#os.path.relpath

>>> import os
>>> full_path = '/book/html/wa/foo/bar/'
>>> print os.path.relpath(full_path, '/book/html')
'wa/foo/bar'

A better answer would be to use os.path.relpath:

http://docs.python.org/3/library/os.path.html#os.path.relpath

>>> import os
>>> full_path = '/book/html/wa/foo/bar/'
>>> relative_path = '/book/html'
>>> print(os.path.relpath(full_path, relative_path))
'wa/foo/bar'
Source Link
Mitch ミッチ
  • 2.5k
  • 2
  • 14
  • 5

A better answer would be to use os.path.relpath:

http://docs.python.org/2/library/os.path.html#os.path.relpath

>>> import os
>>> full_path = '/book/html/wa/foo/bar/'
>>> print os.path.relpath(full_path, '/book/html')
'wa/foo/bar'