'Re-naming multiple files

I have multiple directories inside which there are multiple files.

In directory1 files have the name format:

1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-1-10jd0au.dcm

1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-2-10jd0av.dcm

....

1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-10-17v7m18.dcm

In directory2:

1.2.826.0.1.3680043.2.133.1.3.49.1.46.34440-4-1-r3hu3u.dcm

1.2.826.0.1.3680043.2.133.1.3.49.1.46.34440-4-2-r3hu3v.dcm

....

and so on.

How can I rename these as just 1.dcm, 2.dcm,.....in each directory?

My attempt is as follows:

for dpath, dnames, fnames in os.walk(dir_path):
    for dname in dnames:
        directory = os.path.join(dir_path,dname)
        for filename in os.listdir(directory):
            old_name = os.path.join(directory,filename)
            new = filename[filename.find("-"):]
            new_name = os.path.join(directory, new)
            os.rename(old_name, new_name)

But this only yields:

-3-1-10jd0au.dcm

-3-10-17v7m18.dcm



Solution 1:[1]

You could write a function that uses a regex to extract the parts of the filename that you need, for example:

import re

def ExtractNumber(filename):
  parts = re.search(r".*-.*-(.*)-.*(\..*)", filename)
  return parts.group(1) + parts.group(2)

print(ExtractNumber("1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-1-10jd0au.dcm"))
print(ExtractNumber("1.2.826.0.1.3680043.2.133.1.3.49.1.124.27456-3-10-17v7m18.dcm"))

Outputs:

1.dcm
10.dcm

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Morton