更新时间:2023-02-23 16:50:49
在具有脚本的文件中,您想要执行以下操作:
In the file that has the script, you want to do something like this:
import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')
这将为您提供要查找的文件的绝对路径.请注意,如果您使用的是setuptools,则可能应该使用其包资源API 代替.
This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.
更新:我在这里回应评论,因此我可以粘贴代码示例. :-)
UPDATE: I'm responding to a comment here so I can paste a code sample. :-)
我是否正确地认为
__file__
并不总是可用(例如,当您直接运行文件而不是导入文件时)?
Am I correct in thinking that
__file__
is not always available (e.g. when you run the file directly rather than importing it)?
当您提到直接运行文件时,我假设您的意思是__main__
脚本.如果是这样,在我的系统上似乎不是这种情况(在OS X 10.5.7上为python 2.5.1):
I'm assuming you mean the __main__
script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):
#foo.py
import os
print os.getcwd()
print __file__
#in the interactive interpreter
>>> import foo
/Users/jason
foo.py
#and finally, at the shell:
~ % python foo.py
/Users/jason
foo.py
但是,我确实知道在C扩展名上有一些__file__
的古怪之处.例如,我可以在Mac上执行此操作:
However, I do know that there are some quirks with __file__
on C extensions. For example, I can do this on my Mac:
>>> import collections #note that collections is a C extension in Python 2.5
>>> collections.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-
dynload/collections.so'
但是,这在Windows计算机上引发了异常.
However, this raises an exception on my Windows machine.