Truncate path in Python

Question:

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: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
Asked By: Ghoul Fool

||

Answers:

You were right when you tried to use os.path. You can simply use os.path.split or os.path.basename like this:

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

And just keep doing that as many times as necessary.

Source: this answer

Answered By: Fabián Montero

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')
Answered By: Erik Cederstrand

I know this is an old question and it seems like you are asking about truncating a path based on an integer, however, it’s also pretty easy to truncate based on a folder name.

Here is an example of truncating to the current working directory:

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

Input "/home/user_name/some_folder/inner_folder"

Current Working Directory "some_folder"

Return "./inner_folder"

Maybe there is a built-in way of doing this but idk.

Answered By: DeepFried Oreo
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.