-1

I can extract a string from a .json file: path1 --> "../../Images/PatientID 0/1.2.840.113704.1.111.2716.1398172953.1/1.2.840.113704.1.111.2716.1398173172.21"

The Images folder above is in path2 --> D:\\\\CAP Exam Data\ path(windows). I want to remove the ../../ part and join path1 and path2 to access the file from a python script.

I have tried the following:

path1 = '../../Images/PatientID 0/1.2.840.113704.1.111.2716.1398172953.1/1.2.840.113704.1.111.2716.1398173172.21' 
path2 =  ''D:\\\\CAP Exam Data\

newpath  = os.path.join(path2, path1)
print(newpath)

D:\\CAP Exam Data\../../Images/9111142/1.2.840.113745.101000.100100.2.41057.5995.9117440/1.3.12.2.1107.5.1.4.60044.30000012053010493246800022943

Now how do I remove ../../ part? I tried slicing like [4:] in path1. But nothing seems to work.

Also, how can I fix up the / \ windows, Linux conflict? Is it even an issue?

banikr
  • 63
  • 1
  • 9
  • "Also, how can I fix up the / \ windows, Linux conflict?" Python takes care of that. ``/`` can be used as a system independent separator. – MisterMiyagi Jun 13 '21 at 07:48
  • see: [Python joining current directory and parent directory with os.path.join](https://stackoverflow.com/questions/17295086/python-joining-current-directory-and-parent-directory-with-os-path-join) – Luuk Jun 13 '21 at 07:50
  • You need to join path2+path1, not path1+path2, – azro Jun 13 '21 at 08:00
  • 1
    The easiest way to work with Windows filenames in Python strings is to use raw strings that don't treat \ as an escape, like this: `r"D:\CAP Exam Data"`. And the most friendly module for working with paths is `pathlib`. – BoarGules Jun 13 '21 at 08:16
  • @azro good call, i actually did what you said but wrote it here reversed. Thanks – banikr Jun 13 '21 at 18:14

1 Answers1

0

newpath.replace('\../../', '/')

This worked.

D:\\CAP Exam Data/Images/9111142/1.2.840.113745.101000.100100.2.41057.5995.9117440/1.3.12.2.1107.5.1.4.60044.30000012053010493246800022943

banikr
  • 63
  • 1
  • 9