获取脚本目录名称 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31258561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:43:10 来源:igfitidea点击:
get script directory name - Python
提问by spenf10
I know I can use this to get the full file path
我知道我可以用它来获取完整的文件路径
os.path.dirname(os.path.realpath(__file__))
But I want just the name of the folder, my scrip is in. SO if I have my_script.py and it is located at
但我只想要文件夹的名称,我的脚本在。所以如果我有 my_script.py 并且它位于
/home/user/test/my_script.py
I want to return "test" How could I do this?
我想返回“测试”我该怎么做?
Thanks
谢谢
采纳答案by bytesized
import os
os.path.basename(os.path.dirname(os.path.realpath(__file__)))
Broken down:
分解:
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
回答by Joe T. Boka
>>> import os
>>> os.getcwd()
回答by Subham Debnath
Just write
写就好了
import os
import os.path
print( os.path.basename(os.getcwd()) )
Hope this helps...
希望这可以帮助...