获取脚本目录名-Python

获取脚本目录名-Python,python,file,python-os,getcwd,Python,File,Python Os,Getcwd,我知道我可以用它来获取完整的文件路径 os.path.dirname(os.path.realpath(__file__)) 但我只想知道文件夹的名称,我的纸条在里面。因此,如果我有我的_script.py,它位于 /home/user/test/my_script.py 我想返回“test”我该怎么做 谢谢 细分: currentFile = __file__ # May be 'my_script', or './my_script' or

我知道我可以用它来获取完整的文件路径

os.path.dirname(os.path.realpath(__file__))
但我只想知道文件夹的名称,我的纸条在里面。因此,如果我有我的_script.py,它位于

/home/user/test/my_script.py
我想返回“test”我该怎么做

谢谢

细分:

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()) )

希望这有助于…

返回
/home/user/test/
,而不是
test
。实际上,如果您从另一个目录调用脚本(
cd/home/user;python test/my_script.py
),它甚至不会返回。它将返回您所在的目录(在示例中:
/home/user/
)@bytesized,但OP确实要求获取当前工作目录,这意味着您在运行解释器时所在的当前目录。所以
os.getcwd
正是这样做的。@greatwolf引用了这篇文章,“但我只想知道文件夹的名称,我的纸条就在里面。所以如果我有我的_script.py,它位于
/home/user/test/my_script.py
我想返回'test'。尽管问题的标题是“获取当前目录”,但这并不是OP想要的。这只是返回当前工作目录。因此,无论从哪个位置调用python脚本,都将返回@greatwolf是的,cwd()并没有解决这个问题,因为OP只需要父目录的第一级路径,而不是从根目录开始的所有路径,答案在这里+1
os.path.basename(os.getcwd())
如果只关心运行脚本的目录,也可以使用。
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()) )