Path to current file depends on how I execute the program

让人想犯罪 __ 提交于 2019-12-12 11:01:10

问题


This is my Python program:

#!/usr/bin/env python

import os

BASE_PATH = os.path.dirname(__file__)
print BASE_PATH

If I run this using python myfile.py it prints an empty string. If I run it using myfile.py, it prints the correct path. Why is this? I'm using Windows Vista and Python 2.6.2.


回答1:


It's just a harmless windows quirk; you can compensate by using os.path.abspath(__file__), see the docs




回答2:


os.path.normpath(os.path.join(os.getcwd(),os.path.dirname(__file__)))



回答3:


In many cases it's better to use:

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


来源:https://stackoverflow.com/questions/1483827/path-to-current-file-depends-on-how-i-execute-the-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!