我实际上认为我知道这个问题的答案,它是:
current_working_directory = os.getcwd().split("/")
local_working_directory = current_working_directory[len(current_working_directory)-1]
这对我有用。我检查过的其他帖子(例如:查找当前目录和文件的目录)似乎没有解释如何获取本地目录,而不是整个目录路径。所以将此作为已回答的问题发布。也许问题应该是:我如何发布我已经回答的问题的答案,以帮助其他人?嘿,也许有更好的答案: - )
欢呼声,
-mike: - )
答案 0 :(得分:2)
我会使用basename
import os
path = os.getcwd()
print(os.path.basename(path))
答案 1 :(得分:0)
试试这些
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, relative to os.getcwd()")
print(__file__ + "\n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")
print("This file directory and name")
path, file = os.path.split(full_path)
print(path + ' --> ' + file + "\n")
print("This file directory only")
print(os.path.dirname(full_path))
从这里采取:Find current directory and file's directory
编辑:这是另一个问题
current_folder_name = os.path.split(os.getcwd())
答案 2 :(得分:0)
os.path
包含许多有用的路径操作函数。我想你正在寻找os.path.basename
。最好使用os.path
,因为您的程序将是跨平台的:目前,您的解决方案不适用于Windows。获取您所在目录名称的跨平台方式是
import os
cwd = os.getcwd()
# use os.path.basename instead of your own function!
print(os.path.basename(cwd))
# Evaluates to True if you have Unix-y path separators: try it out!
os.path.basename(cwd) == cwd.split('/')[-1]
>>> True