Home > Mobile >  Rename file name by removing given prefix pattern
Rename file name by removing given prefix pattern

Time:07-06

I have the following files in txt format:

enter image description here

Expected File Format: I want to remove prefix from file name that is 1. a1. and while renaming if the file already present with same name then append _1, _2 to the file as given below in example.

enter image description here

My try:

import os
import re
import shutil
import argparse

pattern = "a1" 
path = "/Users/a1/Documents/Files" 

count = 0

p = ".* " str(pattern) ".(. )"

for root, dirs, files in os.walk(path):

for file in files: 
        
        m = re.match(p, file)

        if m is not None:
            
            file_new = m.group(1)
    
            if not os.path.exists(os.path.join(root,file_new)):
                os.rename(os.path.join(root, file), os.path.join(root,file_new))
            else:
                count = count   1
                file_new = m.group(1) "_" str(count)
                os.rename(os.path.join(root, file), os.path.join(root,file_new))

And this is what the output I'm getting:

enter image description here

CodePudding user response:

You can use Dict for saving the count of repeating each file_name and use saving count in Dict for renaming.

import os
import re

pattern = "a1" 
path = "Files/" 

dct = {}                                                      # <- adding this
for root, dirs, files in os.walk(path):
    for file in files: 
            if pattern in file:
                file_new = file.split(pattern, 1)[1]
                if not file_new in dct:                        # <- adding this
                    os.rename(os.path.join(root, file), 
                              os.path.join(root,file_new[1:]))
                    dct[file_new] = 1                          # <- adding this
                else:
                    num = dct[file_new]                        # <- adding this
                    dct[file_new]  = 1                         # <- adding this
                    file_name, file_type = file_new[1:].split('.')
                    os.rename(os.path.join(root, file), 
                              os.path.join(root, f'{file_name}_{num}.{file_type}'))

Filename before renaming:

enter image description here

Filename after renaming:

enter image description here

  • Related