【问题标题】:Truncate path in Python在 Python 中截断路径
【发布时间】:2018-09-20 06:37:09
【问题描述】:

有没有办法在 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

【问题讨论】:

    标签: python windows python-2.7 path


    【解决方案1】:

    内置的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')
    

    【讨论】:

      【解决方案2】:

      当您尝试使用 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
      

      只要继续这样做,就需要多少次。

      来源:this answer

      【讨论】:

        猜你喜欢
        • 2014-01-16
        • 2017-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-04
        • 2020-05-21
        相关资源
        最近更新 更多