spe*_*f10 32 python file getcwd python-os
我知道我可以使用它来获取完整的文件路径
os.path.dirname(os.path.realpath(__file__))
Run Code Online (Sandbox Code Playgroud)
但是我只想要文件夹的名称,我的脚本就在.如果我有my_script.py并且它位于
/home/user/test/my_script.py
Run Code Online (Sandbox Code Playgroud)
我想回"测试"我怎么能这样做?
谢谢
Joe*_*oka 53
>>> import os
>>> os.getcwd()
Run Code Online (Sandbox Code Playgroud)
byt*_*zed 47
import os
os.path.basename(os.path.dirname(os.path.realpath(__file__)))
Run Code Online (Sandbox Code Playgroud)
细分:
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
Run Code Online (Sandbox Code Playgroud)