有没有办法在Python中截断长路径,使其只显示最后几个目录?我以为我可以使用 os.path.join 来做到这一点,但它只是不能那样工作。 我已经编写了下面的函数,但很想知道是否有更 Pythonic 的方法来执行相同的操作。
#!/usr/bin/python
import os
def shorten_folder_path(afolder, num=2):
s = "...\\"
p = os.path.normpath(afolder)
pathList = p.split(os.sep)
num = len(pathList)-num
folders = pathList[num:]
# os.path.join(folders) # fails obviously
if num*-1 >= len(pathList)-1:
folders = pathList[0:]
s = ""
# join them together
for item in folders:
s += item + "\\"
# remove last slash
return s.rstrip("\\")
print shorten_folder_path(r"C:\temp\afolder\something\project files\more files", 2)
print shorten_folder_path(r"C:\big project folder\important stuff\x\y\z\files of stuff", 1)
print shorten_folder_path(r"C:\folder_A\folder\B_folder_C", 1)
print shorten_folder_path(r"C:\folder_A\folder\B_folder_C", 2)
print shorten_folder_path(r"C:\folder_A\folder\B_folder_C", 3)
...\project files\more files
...\files of stuff
...\B_folder_C
...\folder\B_folder_C
...\folder_A\folder\B_folder_C
最佳答案
内置pathlib模块有一些漂亮的方法可以做到这一点:
>>> from pathlib import Path
>>>
>>> def shorten_path(file_path, length):
... """Split the path into separate parts, select the last
... 'length' elements and join them again"""
... return Path(*Path(file_path).parts[-length:])
...
>>> shorten_path('/path/to/some/very/deep/structure', 2)
PosixPath('deep/structure')
>>> shorten_path('/path/to/some/very/deep/structure', 4)
PosixPath('some/very/deep/structure')
关于python - Python 中的截断路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49757063/