0

I have the following code that renames a certain amount of files that have keywords such as: 'Alamo', 'Portland',..., and a handful of other custom names, and I want to put a number next to it: i.e '76-Alamo' / '77-Portland'

Is there a way to repeat the same code N-times by defining the keywords as strings? something like:

Names = ('Alamo', 'Portland', 'Name3',...,)

Number = ('76', '77', '78',...,)

Code:

import os

os.chdir('.')

for file in os.listdir(): clinic, extension = os.path.splitext(file)

for f in os.listdir():
    if f.startswith('Alamo'):
        old_name = f
        new_name = '{}-{}'.format("76", f)
        os.rename(old_name, new_name)
                    
        for f in os.listdir():
            if f.startswith('Portland'):
                old_name = f
                new_name = '{}-{}'.format("77", f)
                os.rename(old_name, new_name)

I appreciate any insight into this. Please let me know if there's any further details I may provide.

1 Answer 1

1

You could use a dictionary to record the name and the number you want to add and check each key in the dictionary.

rename_dict = {
   'Alamo': 76,
   'Portland': 77,
   'Name3': 78,
   ...
}

for f in os.listdir():
    for keyword in rename_dict.keys():
        if f.startswith(keyword):
            old_name = f
            new_name = '{}-{}'.format(str(rename_dict[keyword]), f)
            os.rename(old_name, new_name)

Alternatively, if you know the numbers for each keyword will increment by one each time, you can store each keyword in a list and use the index of that keyword plus an offset.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.