如何在python中获得当前的本地目录

2024-09-29 17:23:26 发布

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

我真的认为我知道答案,而且是:

current_working_directory = os.getcwd().split("/")
local_working_directory = current_working_directory[len(current_working_directory)-1]

这对我有用。我看过的其他帖子(例如:findcurrentdirectory和file'sdirectory)似乎都没有解释如何获得本地目录,而不是整个目录路径。所以把这个贴在已经回答的问题上。也许问题应该是:我如何发布我已经回答过的问题的答案,以便帮助其他人?嘿,也许还有更好的答案:-)


Tags: 答案路径目录lenoslocalcurrentdirectory
3条回答

我会使用basename

import os

path = os.getcwd()
print(os.path.basename(path))

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

试试这些

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

编辑:这是另一个问题

^{pr2}$

相关问题 更多 >

    热门问题