get script directory name - Python
我知道我可以用这个获取完整的文件路径
1 | os.path.dirname(os.path.realpath(__file__)) |
但我只想要文件夹的名字,我的便签在里面。所以,如果我有我的"script.py"并且它位于
1 | /home/user/test/my_script.py |
我想返回"测试",我该怎么做?
谢谢
1 2 | >>> import os >>> os.getcwd() |
1 2 | import os os.path.basename(os.path.dirname(os.path.realpath(__file__))) |
分解:
1 2 3 4 5 6 | 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 |
只写
1 2 3 | import os import os.path print( os.path.basename(os.getcwd()) ) |
希望这有帮助…