获取脚本目录名-Python

2024-10-03 04:28:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

os.path.dirname(os.path.realpath(__file__))

但我要的只是文件夹的名字,我的纸条在里面。所以如果我有我的脚本,它位于

/home/user/test/my_script.py

我想返回“测试”我怎么能这样做?

谢谢


Tags: 文件pathtest路径脚本文件夹homeos
3条回答
>>> import os
>>> os.getcwd()

就写吧

import os
import os.path
print( os.path.basename(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

相关问题 更多 >