When to use Absolute Path vs Relative Path in Python

前端 未结 2 694
栀梦
栀梦 2020-12-17 23:44

For reference. The absolute path is the full path to some place on your computer. The relative path is the path to some file with respect to your current working directory (

相关标签:
2条回答
  • 2020-12-17 23:57

    The biggest consideration is probably portability. If you move your code to a different computer and you need to access some other file, where will that other file be? If it will be in the same location relative to your program, use a relative address. If it will be in the same absolute location, use an absolute address.

    0 讨论(0)
  • 2020-12-18 00:03

    If you don't know where the user will be executing the script from, it is best to compute the absolute path on the user's system using os and __file__.

    __file__ is a global variable set on every Python script that returns the relative path to the *.py file that contains it.

    import os
    my_absolute_dirpath = os.path.abspath(os.path.dirname(__file__))
    
    0 讨论(0)
提交回复
热议问题