How does one rename multiple files within folders using python?

304 views Asked by At

I have over 1000 folders in 'my documents'. In each folder there are only 4 photos that need to be named to 'North' 'East' 'South' and 'West' in that order. Currently they are named DSC_XXXX. I have written this script but it is not executing.

import sys, os

folder_list = []
old_file_list = []
newnames = [North, South, East, West]

for file in os.listdir(sys.argv[1]):
    folder_list.append(file)

 for i in range(len(folder_list)):
    file = open(folder_list[i], r+)
    for file in os.listdir(sys.argv[1] + '/' folder_list[i]):
       old_file_list.append(file)
       os.rename(old_file_list, newnames[i])

My method of thinking was to get all the names of the 1000 folders and store them in folder_list. Then open each folder and save the 4 picture names in old_file_list. From there I would like to use the os.rename(old_file_list, newnames[i]) to rename the 4 photos to North East South and West. Then I want this to loop for as many folders that are in 'my documents'. I am new to python and any help or suggestions would be greatly appreciated.

2

There are 2 answers

5
Daniel On BEST ANSWER

You don't need all the lists, just rename all files on the fly.

import sys, os, glob

newnames = ["North", "South", "East", "West"]

for folder_name in glob.glob(sys.argv[1]):
    for new_name, old_name in zip(newnames, sorted(os.listdir(folder_name))):
       os.rename(os.path.join(folder_name, old_name), os.path.join(folder_name, new_name))
2
Ethan Furman On

Here's how I would do it using antipathy [1]:

# untested

from antipathy import Path

def check_folder(folder):
    "returns four file names sorted alphebetically, or None if file names do not match criteria"
    found = folder.listdir()
    if len(found) != 4:
        return None
    elif not all(fn.startswith('DSC_') for fn in found):
        return None
    else:
        return sorted(found)

def rename(folder, files):
    "rename the four files from DSC_* to North East South West, keeping the extension"
    for old, new in zip(files, ('North', 'East', 'South', 'West')):
        new += old.ext
        folder.rename(old, new)

if __name__ == '__main__':
    for name in Path.listdir(sys.argv[1]):
        if not name.isdir():
            continue
        files = check_folder(name)
        if files is None:
            continue
        rename(name, files)

[1] disclaimer: antipathy is one of my projects