在 Python 中截断路径



有没有办法在Python中截断长路径,使其仅显示最后几个左右的目录?我以为我可以使用 os.path.join 来做到这一点,但它就是不能那样工作。我已经在下面编写了函数,但很想知道是否有一种更 Python 的方式来做同样的事情。

#!/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:tempafoldersomethingproject filesmore files", 2)
print shorten_folder_path(r"C:big project folderimportant stuffxyzfiles of stuff", 1)
print shorten_folder_path(r"C:folder_AfolderB_folder_C", 1)
print shorten_folder_path(r"C:folder_AfolderB_folder_C", 2)
print shorten_folder_path(r"C:folder_AfolderB_folder_C", 3)

...project filesmore files
...files of stuff
...B_folder_C
...folderB_folder_C
...folder_AfolderB_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')

当你尝试使用os.path时,你是对的。您可以简单地使用这样的os.path.splitos.path.basename

fileInLongPath = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0]) # this will get the first file in the last directory of your path
os.path.dirname(fileInLongPath) # this will get directory of file
os.path.dirname(os.path.dirname(fileInLongPath)) # this will get the directory of the directory of the file

并根据需要继续这样做。

来源:这个答案

我知道这是一个

老问题,似乎您正在询问基于整数截断路径的问题,但是,根据文件夹名称截断也很容易。

下面是截断到当前工作目录的示例:

import os
from os import path as ospath
from os.path import join
def ShortenPath(path):
    split_path = ospath.split("/")
    cwd = os.getcwd().split("/")[-1]
    n = [x for x in range(len(split_path)) if split_path[x] == cwd]
    n = n[0] if n != [] else -1
    return join(".", *[d for d in split_path if split_path.index(d) > n]) if n >= 0 else path

输入"/home/user_name/some_folder/inner_folder"

当前工作目录"some_folder"

返回"./inner_folder"

也许有一种内置的方法可以做到这一点,但是idk。

相关内容

  • 没有找到相关文章

最新更新