Domanda

I have a bit of a tricky one to solve. I have the need to extract a specific portion of a file path. I've extracted a zip file under a temp directory have have the full path to the file. Essentially what I would like is to get the difference between the full file path and the temp path. Let me give an example below:

Fullpath = c:\\users\\test\\appdata\\local\\temp\\tempDir\\common\\test.txt

TempPath = c:\\users\\test\\appdata\\local\\temp\\tempDir\\

So my expected results would be to have the following:

results = \\common\\test.txt

Just looking for an easy, Pythonic way to accomplish this.

È stato utile?

Soluzione

You can use os.path.relpath:

os.path.relpath(Fullpath, TempPath)

Or you can use split:

Fullpath.split(TempPath)[1]

Or you can use commonprefix with replace as:

Fullpath.replace(os.path.commonprefix([Fullpath, TempPath]),'')

Output:

common\test.txt

Altri suggerimenti

results = '\\' + Fullpath.replace(TempPath, '')

Or if you want to be sure to remove the beginning of the string:

import re
results = '\\' + re.sub('^%s' % TempPath, '', Fullpath)

A less than fully robust way is to use os.path.commonprefix:

import os

Fullpath = 'c:\\users\\test\\appdata\\local\\temp\\tempDir\\common\\test.txt'
TempPath = 'c:\\users\\test\\appdata\\local\\temp\\tempDir\\'

print os.path.commonprefix([Fullpath, TempPath])
# c:\users\test\appdata\local\temp\tempDir\

Be aware thought that the function does not know anything about paths; it is just a character by character deal.

Then use str.partition to get the part you are interested in:

>>> print Fullpath.partition(os.path.commonprefix([Fullpath, TempPath]))
('', 'c:\\users\\test\\appdata\\local\\temp\\tempDir\\', 'common\\test.txt')

If you have a situation like so:

Fullpath = 'c:\\users\\test\\appdata\\local\\temp\\tempDir\\common\\test.txt'
TempPath = 'c:\\users\\test\\appdata\\local\\temp\\tempDir\\co'  

It is better to wrap the common prefix with os.path.dirname

>>> os.path.dirname(os.path.commonprefix([Fullpath, TempPath]))
c:\users\test\appdata\local\temp\tempDir\

But that still does not fix a situation like this:

Fullpath = 'c:\\users\\test\\..\\test\\appdata\\local\\temp\\tempDir\\common\\test.txt'

Where you need to resolve full absolute path names before parsing.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top