Baldev
Baldev

Reputation: 25

How to use wildcard in renaming multiple files in a directory in Python

I am new to coding. Is it possible to use wildcard for renaming a file in a directory?

example there are two files in a folder:

asdxyd01.pdf

cdc1pxych001.pdf

want to rename the file by removing the all characters before "xy".

i am using the following code which is working great for removing the specific words only.

# Function to replace words in files names in a folder
import os
def main():
    i = 0

    # Ask user where the PDFs are
    path = input('Folder path to PDFs: ')
    # Sets the scripts working directory to the location of the PDFs
    os.chdir(path)
    
    filetype = input('entre file extention here: ')
    rep = input('entre word to remove from file name: ')

    for filename in os.listdir(path):
                        
        my_dest = filename.replace(rep, "") +"."+filetype
                
        my_source = filename
        my_dest = my_dest
        # rename() function will
        # rename all the files
        os.rename(my_source, my_dest)
        i += 1


# Driver Code
if __name__ == '__main__':
    # Calling main() function
    main()

Upvotes: 1

Views: 1124

Answers (1)

Ankush Pandit
Ankush Pandit

Reputation: 396

Judging by your question, I assume that you want your files to be renamed as: xyd01.pdf, ch001.pdf. Firstly, let's look at your mistake:

my_dest = filename.replace(rep, "") +"."+filetype

Here by replacing 'rep' with '' you are basically deleting the pattern from name, not the characters before it. So, to achieve your goal you need to find the occurrence of your matching pattern and replace the substring before it. You can do this by:

index=filename.find(rep)
prefix=filename[:index]
my_dest = filename.replace(prefix, "")

Look, that I haven't added "."+filetype at the end of destination either, cause it will make the replace file look like this: xyd01.pdf.pdf.

Now you should keep some more things in consideration while running this code. If you do not put any checking at the very beginning of for loop, your program will rename any file name having the same pattern, so add this below condition also:

 if filetype not in filename:
         continue

Finally another checking is important to prevent invalid array index while slicing the file name:

    index=filename.find(rep)
    if index<=0:
        continue

Overall looks like this:

for filename in os.listdir(path):
    if filetype not in filename:
        continue
    index=filename.find(rep)
    if index<=0:
        continue
    prefix=filename[:index]
    my_dest = filename.replace(prefix, "")                                            
    my_source = filename
    os.rename(my_source, my_dest)
    i += 1 # this increment isn't necessary

Upvotes: 2

Related Questions