Python: Get relative path from comparing two absolute paths -


Say, I have two complete paths. I need to check whether any reference to one of the places is related to another Belongs to descent. If true, then I have to find out the relative path of the offspring from the ancestors. What is a good way to implement it in Python?

and your friends are:

  & gt; & Gt; & Gt; Print os.path.commonprefix (['/ usr / var / log', '/ usr / var / security']) '/ usr / var' & gt; & Gt; & Gt; Print os.path.commonprefix (['/ tmp', '/ usr / var']) # is not a normal prefix: root is a normal prefix '/'   

What can be tested is one of the common prefix paths, i.e. if one of the paths is common ancestor:

  path = [[?] |, |? | |, One | | Common_prefix = Os.path.commonprefix (list_of_paths) if paths in common_prefix: a ?? |   

You can find the relative path:

  relative_paths = [os.path.relpath (path, common_prefix) for paths in the path]   

You can handle more than two routes along with this method, and check that all paths are given below or not

PS : Depending on how you look your way, you want to do some generalization first (it is useful in situations where nobody knows if they are always finished Ote are '/' or not, or if a relative path). Are involved in relevant tasks and

PPS : As Peter Briggs described in the comments, the simple approach described above may fail:

  & gt; & Gt; ; & Gt; Os.path.commonprefix (['/ usr / var', '/ usr / var2 / log']) '/ usr / var'   

even if / usr / var A common prefix of paths is not

PPPS : As mentioned bluenote10, adding a word Slash does not solve common problem here. Here's his next question:

PPPPS : When we start with Python 3.4 we have a module that provides a Sinner Path manipulation environment is. I think the normal prefix of one set of path can be achieved by taking all the prefixes (along with) of each path, all these parents, with the inclination of the set and for the longest selection of the general prefix.

PPPPPS : Python 3.5 has presented the appropriate solution to this question, which gives a valid path.

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

c# - Confused over DLL entry points (entry point not found exception) -