How to get full path of current file's directory in Python?
I want to get the current file's directory path.
I tried:
>>> os.path.abspath(__file__)
'C:python27test.py'
But how can I retrieve the directory's path? For example:
'C:python27'
If you mean the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.getcwd()
Note that before and after file
is two underscores, not just one.
import os
print os.path.dirname(__file__)
You can use os
and os.path
library easily as follows
import os
os.chdir(os.path.dirname(os.getcwd()))
os.path.dirname
returns upper directory from current one. It lets us change to an upper level without passing any file argument and without knowing absolute path.
上一篇: Python:我在运行什么操作系统?