Home > Net >  Filename replacing; creating a loop by defining a string list
Filename replacing; creating a loop by defining a string list

Time:04-06

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.

CodePudding user response:

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.

  • Related