Relative paths in Python

前端 未结 15 1658
陌清茗
陌清茗 2020-11-22 07:39

I\'m building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don\'t, however, have the absolute path

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 08:13

    summary of the most important commands

    >>> import os
    >>> os.path.join('/home/user/tmp', 'subfolder')
    '/home/user/tmp/subfolder'
    >>> os.path.normpath('/home/user/tmp/../test/..')
    '/home/user'
    >>> os.path.relpath('/home/user/tmp', '/home/user')
    'tmp'
    >>> os.path.isabs('/home/user/tmp')
    True
    >>> os.path.isabs('/tmp')
    True
    >>> os.path.isabs('tmp')
    False
    >>> os.path.isabs('./../tmp')
    False
    >>> os.path.realpath('/home/user/tmp/../test/..') # follows symbolic links
    '/home/user'
    

    A detailed description is found in the docs. These are linux paths. Windows should work analogous.

提交回复
热议问题