Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate path in Python

Is there a way to truncate a long path in Python so it only displays the last couple or so directories? I thought I could use os.path.join to do this, but it just doesn't work like that. I've written the function below, but was curious to know if there is a more Pythonic way of doing the same.

#!/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
like image 454
Ghoul Fool Avatar asked Jan 28 '23 08:01

Ghoul Fool


1 Answers

The built-in pathlib module has some nifty methods to do this:

>>> 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')
like image 70
Erik Cederstrand Avatar answered Jan 31 '23 09:01

Erik Cederstrand