Shortening file paths using Python

969 Views Asked by At

I have an application which should display to the user the path to a file. Let's say the user inputs /home/me/foo/, the application should shorten that to ~/foo.

Is there any way to do this in Python such that it works cross-platform with Linux and Windows?

1

There are 1 best solutions below

2
algorythms On BEST ANSWER

now sure what you are trying to do but changing it to the other format is as simple as:

newpath = "~"+filepath[9:]

if you want this to work with other usernames,

newpath = "~/"+filepath[findfirstindex('foo'):]