获取脚本目录名称

我知道我可以使用它来获取完整的文件路径

os.path.dirname(os.path.realpath(__file__))

但我只想要文件夹的名称,我的脚本是在。如果我有my_script.py,它位于

/home/user/test/my_script.py

我想返回“测试”我怎么能做到这一点?

谢谢


import os
os.path.basename(os.path.dirname(os.path.realpath(__file__)))

分解:

currentFile = __file__  # May be 'my_script', or './my_script' or
                        # '/home/user/test/my_script.py' depending on exactly how
                        # the script was run/loaded.
realPath = os.path.realpath(currentFile)  # /home/user/test/my_script.py
dirPath = os.path.dirname(realPath)  # /home/user/test
dirName = os.path.basename(dirPath) # test

>>> import os
>>> os.getcwd()

写吧

import os
import os.path
print( os.path.basename(os.getcwd()) )

希望这可以帮助...

链接地址: http://www.djcxy.com/p/54709.html

上一篇: get script directory name

下一篇: how do you get the current local directory in python