2

I have .dcm files in a path like below (old_path);

old_path: Mass-Test_P_00016_LEFT_MLO_1/10-04-2016-DDSM-15563/1-cropped images-77287/000000.dcm 

I have to rename the path like below (good_path);

good_path: Mass-Test_P_00016_LEFT_MLO_1/15563/77287/000000.dcm 

Note that I keep only the last 5 digits in the sub-folders as shown above.

Please anyone show me how this must be done? This is my attempt...

os.chdir(path to data) os.listdir() >> ['Mass-Test_P_00016_LEFT_MLO_1', 'Mass-Test_P_00016_LEFT_MLO'] temp = os.walk('Mass-Test_P_00016_LEFT_MLO_1', topdown=False) for root, dirs, files in temp: for name in files: old_path = os.path.join(root, name) print("old_path: ", old_path) first = old_path.split('/')[1][-5:] second = old_path.split('/')[2][-5:] #print(first, second) good_path = os.path.join(old_path.split('/')[0], first, second, old_path.split('/')[3]) print("good_path: ", good_path) os.rename(old_path, good_path) 

I was able to set the good_path as I want. But it is not overwriting the subfolders names.

7
  • 2
    Suggest you use os.path.split() to split paths (instead of e.g. old_path.split('/')). Commented Mar 19, 2020 at 20:44
  • What happens when you run your code? What do you want it to do differently? Commented Mar 19, 2020 at 20:50
  • Tip: set the result of old_path.split('/') to a variable so you don't have to keep calling it. Commented Mar 19, 2020 at 20:51
  • @Code-Apprentice. I get the following error. But there is no issue with the file location. FileNotFoundError: [Errno 2] No such file or directory: 'Mass-Test_P_00016_LEFT_MLO_1/10-04-2016-DDSM-15563/1-cropped images-77287/000000.dcm' -> 'Mass-Test_P_00016_LEFT_MLO_1/15563/77287/000000.dcm' Commented Mar 19, 2020 at 21:18
  • The error says the file you are trying to rename doesn't exist. Likely the problem is because you are using a relative path. So the file you think you are renaming isn't the actual file that the program is actually renaming. Commented Mar 19, 2020 at 21:21

1 Answer 1

3

You need to rename each node of your path from the root (the left most folder of old_path) to the leaf (your .dcm file). You might be interested in using os.renames instead of os.rename

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.