pythonparsingfilepathfileparsingfileparse

Easiest way to get a specific section of a file path


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.


Solution

  • 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