how do you get the current local directory in python
本问题已经有最佳答案,请猛点这里访问。
我想我知道答案,它是:
1 2 | current_working_directory = os.getcwd().split("/") local_working_directory = current_working_directory[len(current_working_directory)-1] |
这对我有用。我签出的其他文章(例如:查找当前目录和文件目录)似乎都没有解释如何获取本地目录,而不是整个目录路径。所以把它作为一个已经回答的问题发布。也许问题应该是:为了帮助别人,我应该如何把答案贴在我已经回答过的问题上?嘿,也许还有更好的答案:—)
干杯,
-迈克:
我会用
1 2 3 4 | import os path = os.getcwd() print(os.path.basename(path)) |
1 2 3 4 5 6 7 8 9 | 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 |
试试这些
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import os print("Path at terminal when executing this file") print(os.getcwd() +" ") print("This file path, relative to os.getcwd()") print(__file__ +" ") print("This file full path (following symlinks)") full_path = os.path.realpath(__file__) print(full_path +" ") print("This file directory and name") path, file = os.path.split(full_path) print(path + ' --> ' + file +" ") print("This file directory only") print(os.path.dirname(full_path)) |
从此处获取:查找当前目录和文件目录
编辑:这是那个问题的另一个问题
1 | current_folder_name = os.path.split(os.getcwd()) |