获取脚本目录名称 - Python
get script directory name - Python
我知道我可以用它来获取完整的文件路径
os.path.dirname(os.path.realpath(__file__))
但我只想要文件夹的名称,我的凭证在里面。所以如果我有 my_script.py 并且它位于
/home/user/test/my_script.py
我想 return "test" 我该怎么做?
谢谢
>>> import os
>>> os.getcwd()
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
import os.path
print( os.path.basename(os.getcwd()) )
希望这对您有所帮助...
我知道我可以用它来获取完整的文件路径
os.path.dirname(os.path.realpath(__file__))
但我只想要文件夹的名称,我的凭证在里面。所以如果我有 my_script.py 并且它位于
/home/user/test/my_script.py
我想 return "test" 我该怎么做?
谢谢
>>> import os
>>> os.getcwd()
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
import os.path
print( os.path.basename(os.getcwd()) )
希望这对您有所帮助...