pythoncross-platformfilepathpath-separator

Shortening file paths using Python


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?


Solution

  • 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'):]