How do I get the path of the current executed file in Python?

前端 未结 13 2386
天命终不由人
天命终不由人 2020-11-22 17:06

This may seem like a newbie question, but it is not. Some common approaches don\'t work in all cases:

sys.argv[0]

This means using path = os.path.abs

13条回答
  •  庸人自扰
    2020-11-22 17:38

    You have simply called:

    path = os.path.abspath(os.path.dirname(sys.argv[0]))
    

    instead of:

    path = os.path.dirname(os.path.abspath(sys.argv[0]))
    

    abspath() gives you the absolute path of sys.argv[0] (the filename your code is in) and dirname() returns the directory path without the filename.

提交回复
热议问题