如何以绝对方式获取文件的路径

How to get the path of a file, in an absolut way

如果我在 /home/usr 并且我调用 python /usr/local/rcom/bin/something.py

如何让something.py里面的脚本知道他住在/usr/local/rcom/bin?
os.path.abspath 是用 cwd 计算的,在这种情况下是 /home/usr

里面 something.py:

import os
print os.path.dirname(__file__)

请注意,这仅在您使用绝对路径调用 something.py 时才有效。如果您使用相对路径(例如 scripts/something.py),您需要将代码更改为:

import os
print os.path.dirname(os.path.abspath(__file__))

您可以依赖 script/module 的 __file__ 属性。

import os

path, filename = os.path.split(os.path.abspath(__file__))
print path

打印

 /usr/local/rcom/bin

如果在您的 something.py.

中执行

编辑:是的,您需要考虑绝对路径 ;-),即 os.path.abspath