-1

I've used the Python 3 code below to change files with names like:

CT-8873-0002 CT-8873-0003 ...

to names like

CT-008-0002.dcm CT-008-0003.dcm ...

But I need to change the names to the new names in the actual directory. Can't seem to do this. Tried many things.

    from __future__ import print_function
    import os
    os.chdir('C:\\Users\\franc\\Desktop\\CT-INSPIRIUM-8873')   
    import glob 
    for fileName1 in glob.glob('CT-*'):
            fileName1 = fileName1.split('-')
            fileName1[1] = '008'
            fileName1 = '-'.join(fileName1)
            fileName2 = fileName1
     print(fileName2)

Thanks

  • Have you tried searching on stackoverflow? Because there is this answer: https://stackoverflow.com/questions/2759067/rename-multiple-files-in-a-directory-in-python#2759130 – jjj Feb 23 '18 at 22:35
  • 1
    Possible duplicate of [Rename multiple files in Python](https://stackoverflow.com/questions/17748228/rename-multiple-files-in-python) – jjj Feb 23 '18 at 22:41
  • The files are initially listed in Windows 10 without .dcm and listed vertically – otto diagnosis Feb 23 '18 at 22:56

2 Answers2

0

Your code just creates a new string fileName2 and print it out, it doesn't change your existing files names.

One solution is wrap mv command by python:

import os
os.system('mv original_filename new_filename')

In your case:

 for fileName1 in glob.glob('CT-*'):
     fileName1 = fileName1.split('-')
     fileName1[1] = '008'
     fileName1 = '-'.join(fileName1)
     fileName2 = fileName1

     // add below
     os.system('mv {old_name} {new_name}'.format(old_name=fileName1, new_name=fileName2))

Make sure test your code before execute it on your real data file

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125
0

As I commented on @haifzhan answer, if you are already using python3, you have in fact many methods available for file or directory renaming hidden within the os module. Depending on your exact problem, you can either use os.renames, os.rename or os.replace. Per the python documentation, os.replace is better cross-platform-wise. Which means that your code could simply be:

import os

for fileName1 in glob.glob('CT-*'):
     fileName2 = fileName1.split('-')
     fileName2[1] = '008'
     fileName2 = '-'.join(fileName2)
     # Does the renaming
     os.replace(fileName1, fileName2)
domochevski
  • 553
  • 5
  • 13