获取脚本目录名称 - Python

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)

  • 这将返回`/ home/user/test /`,而不是`test`. (6认同)
  • 实际上,如果你从另一个目录(`cd/home/user; python test/my_script.py`)调用你的脚本,它甚至都不会返回.它将返回您所在的目录(在示例中:`/ home/user /`) (3认同)
  • @bytesized但OP确实要求获取*当前工作目录*,这意味着您在运行解释器时所在的当前目录.所以`os.getcwd`正是这样做的. (2认同)
  • @greatwolf引用OP,"但我只想要文件夹的名称,我的脚本就在.如果我有my_script.py并且它位于`/ home/user/test/my_script.py`我想要返回'测试'".虽然问题的标题是"获取当前目录",但这不是OP想要的. (2认同)
  • 这只是返回当前的工作目录。因此,无论您从哪个位置调用 python 脚本,都将返回。@greatwolf 所以是的,cwd() 不能解决问题,因为 OP 只想要父目录的第一级路径,而不是从根目录开始,也就是“/” (2认同)

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)

  • 如果您只关心运行脚本的目录,那么+`os.path.basename(os.getcwd())`也可以. (7认同)