Reputation: 83
I have a python script that looks at all the files within a folder for a specific word and replaces that word with a space. Instead of changing the words to look at after each time running the script, I'd like to continue to add new words for the script to look for and perform the same replace action.
I'm 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.
Upvotes: 3
Views: 4327
Reputation: 1696
Whenever you see yourself using blocks of code again and again with just one change, it's usually best to turn them into functions.
Defining functions is quick and easy in Python. They need to be defined before you use them, so usually they go at the top of the file after the import statements.
The syntax looks like this:
def func_name(paramater1,paramater2...):
Then all the code of the function is indented under the def
clause.
I would recommend you put the for path in paths
statement and all that was under it as part of the function, and pass in the word you want to search for as a parameter.
Then, after defining the function, you could make a list of all the words you want to replace in the file names, and run the function as so:
word_list = [.File, Generic]
for word in word_list:
my_function(word)
Upvotes: 1
Reputation: 10359
Use a dictionary to track your replacements. You can then loop over its keys and values, like so:
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 all of your replacements in one go, and only renames the files once.
Upvotes: 8