I have a lot of like abc_model1.pdb.1,...,abc_model1.pdb.100. I want to change these files as abc_model1_1.pdb , ...,abc_model1_100.pdb. I tried several unsuccessful attempts to modify codes as given in 'How do I rename the extension for a batch of files?'. How can I do using python?
            Asked
            
        
        
            Active
            
        
            Viewed 382 times
        
    0
            
            
        - 
                    If you have the `rename` utility (the one from the `perl` package, _not_ the one from util-linux) installed, then all you need is the simple command: `rename 's/\.pdb\.(\d+)$/_$1.pdb/' *` – John1024 Jan 26 '15 at 04:54
1 Answers
1
            
            
        Try this:
import glob
import os
import shutil
file_dir = '/user/foo/bar/somewhere/'
dest_dir = file_dir # Change this to where you want
                    # the renamed files to go.
for file in glob.iglob(os.path.join(file_dir,'*.pdb.*')):
    filename_temp, number = os.path.splitext(os.path.basename(file))
    filename, ext = os.path.splitext(filename_temp)
    shutil.move(file, os.path.join(dest_dir,
                             '{}_{}{}'.format(filename,number,ext)))
 
    
    
        Burhan Khalid
        
- 169,990
- 18
- 245
- 284
- 
                    1Looks like you've only got one argument in your call to `shutil.move` there. – jez Jan 26 '15 at 04:25
- 
                    
- 
                    
- 
                    It uses `os.rename` when required: _"If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied (using shutil.copy2()) to dst and then removed."_ [docs](https://docs.python.org/2/library/shutil.html#shutil.move). – Burhan Khalid Jan 26 '15 at 04:37
 
    