Python Script to remove characters and replace in filenames

I have a python script that loops through all the files in a folder for a specific word and replaces that word with a space. Rather than changing the words to look for after each script run, I would like to continue adding new words for the script to find and perform the same replace action.

I am running this on macOS El Capitan. Below is the script:

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('/Users/Test/Desktop/Test')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('.File',' ')
    if newname != path:
        os.rename(path, newname)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('Generic',' ')
    if newname != path:
        os.rename(path, newname)

      

Any help you can provide to this newbie would be appreciated.

+3


source to share


2 answers


Use a dictionary to keep track of your notes. Then you can iterate over its keys and values, for example:

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('/Users/Test/Desktop/Test')
        for filename in filenames)

# The keys of the dictionary are the values to replace, each corresponding
# item is the string to replace it with
replacements = {'.File': ' ',
                'Generic': ' '}

for path in paths:
    # Copy the path name to apply changes (if any) to
    newname = path 
    # Loop over the dictionary elements, applying the replacements
    for k, v in replacements.items():
        newname = newname.replace(k, v)
    if newname != path:
        os.rename(path, newname)

      



This applies to all your replacements in one go and renames the files only once.

+5


source


Whenever you see yourself using a block of code with one change over and over again, it is usually best to turn them into functions.

Defining functions in Python is quick and easy. They must be defined before they can be used, so they usually appear at the top of the file after import statements.

The syntax is as follows:

def func_name(paramater1,paramater2...):



Then the entire function code is indented as suggested def

.

I would recommend that you put the operator for path in paths

and everything below it as part of the function, and pass the word you want to search for as a parameter.

Then, after defining the function, you can list all the words you want to replace in the filenames and run the function like this:

word_list = [.File, Generic]
for word in word_list:
    my_function(word)

      

+1


source







All Articles