0

I have a series of absolute folder paths that have the following pattern:

  • "C:\Work\Project1\sourcedata"
  • "C:\Work\Project1\scripts"
  • "C:\Work\Project1\outputs\4"
  • "C:\Work\Project1\outputs\3"
  • "C:\Work\Project1\outputs\1"
  • "C:\Work\Project1\outputs\1\hello"

I need to extract the relative paths in comparison to the folder path: - "C:\Work\Project1"

Resulting in:

  • "sourcedata"
  • "scripts"
  • "outputs\4"
  • "outputs\3"
  • "outputs\1"
  • "outputs\1\hello"

Is there a method of doing this using os?

OfficialBenWhite
  • 141
  • 2
  • 12

1 Answers1

2

You can use pathlib to manipulate paths, starting with Python 3.4:

from pathlib import WindowsPath

WindowsPath(r"C:\Work\Project1\sourcedata").relative_to(r"C:\Work\Project1")
# WindowsPath('sourcedata')

WindowsPath(r"C:\Work\Project1\outputs\1\hello").relative_to(r"C:\Work\Project1")
# WindowsPath('outputs/1/hello')
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50