Python 如何以绝对的方式获取文件的路径
如果我在/home/usr中,我调用python/usr/local/rcom/bin/something.py 如何使something.py中的脚本知道他驻留在/usr/local/rcom/bin中? 在本例中,os.path.abspath使用cwd计算,cwd为/home/usr。在something.py中:Python 如何以绝对的方式获取文件的路径,python,file,python-3.x,path,Python,File,Python 3.x,Path,如果我在/home/usr中,我调用python/usr/local/rcom/bin/something.py 如何使something.py中的脚本知道他驻留在/usr/local/rcom/bin中? 在本例中,os.path.abspath使用cwd计算,cwd为/home/usr。在something.py中: import os print os.path.dirname(__file__) 请注意,只有使用something.py的绝对路径调用它时,这才有效。如果使用相对路径ex
import os
print os.path.dirname(__file__)
请注意,只有使用something.py的绝对路径调用它时,这才有效。如果使用相对路径ex.scripts/something.py,则需要将代码更改为:
import os
print os.path.dirname(os.path.abspath(__file__))
您可以依赖脚本/模块的_文件_属性
import os
path, filename = os.path.split(os.path.abspath(__file__))
print path
印刷品
/usr/local/rcom/bin
如果在您的something.py中执行
<>编辑:是的,你需要考虑绝对路径;i、 e.os.path.abspath