38

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

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

但我只想要文件夹的名称,我的脚本就在里面。所以如果我有 my_script.py 并且它位于

/home/user/test/my_script.py

我想返回“测试”我该怎么做?

谢谢

4

3 回答 3

55
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
于 2015-07-07T02:03:17.200 回答
50
>>> import os
>>> os.getcwd()
于 2015-07-07T02:02:59.380 回答
-3

写吧

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

希望这可以帮助...

于 2018-04-26T09:29:12.057 回答