在 Python 中截断路径

Gho*_*ool 4 python windows path python-2.7

有没有办法在 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
Run Code Online (Sandbox Code Playgroud)

Eri*_*and 7

内置的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')
Run Code Online (Sandbox Code Playgroud)


mac*_*azo 1

当您尝试使用时,您是对的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
Run Code Online (Sandbox Code Playgroud)

只要有必要就继续这样做。

来源:这个答案