I need to display a path within a GUI application. Displaying the whole path would be an overkill, so I made a custom path shortener.
def cut_path(path): ''' This function takes a path and outputs the path cut with the ... after the the first folder after the first character and completes the name with the filename or the last folder Example: C:/Users/Mauro/Desktop/DenoiseAvg/DenoiseAverage/test_cut_path.py C:/Users/.../test_cut_path.py ''' endidx = 5 char = path[endidx] while char != '/' and endidx < len(path): endidx += 1 char = path[endidx] inpath = path[:endidx + 1 ] rpath = path[::-1] idx = 1 char = rpath[idx] while char != "/" and idx < len(rpath): idx += 1 char = rpath[idx] endpath = path[len(path) - idx - 1 : ] outpath = inpath + "..." + endpath return outpath
Is there a shorter, more readable, pythonic way to do it? Is there a way to limit how many characters the path would be long? How would you do it?