How can I rename multiple files in folders using python?

I have over 1000 folders in "my documents". There are only 4 photos in each folder, which must be named "North", "East", "South" and "West" in that order. They are currently called DSC_XXXX. I wrote this script but it fails.

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 1000 folder names and store them in a folder folder. Then open each folder and save the 4 image names in old_file_list. From there, I would like to use os.rename (old_file_list, newnames [i]) to rename 4 photos to North East South and West. Then I want this loop to have as many folders as in "my documents". I am new to python and any help or suggestions would be greatly appreciated.

+3


source to share


2 answers


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))

      

+3


source


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

- one of my projects

+1


source







All Articles