3

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.

3
  • If the new names apply "in that order," you'll need to sort the folder's contents first, because os.listdir returns an arbitrarily-ordered list. Also, you can iterate directly over folder_list instead of using range(len()) to work with indices. Commented Jun 10, 2015 at 20:14
  • Oh, and os.listdir() already returns a list, so you don't need to iterate over it and build a new one. Just save a reference to it: folder_list = os.listdir(sys.argv[1]). Commented Jun 10, 2015 at 20:16
  • Also, you don't need to open() folders... although you're masking it with the loop variable anyway. Commented Jun 10, 2015 at 20:19

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but I am confused. If I don't need lists how do I define old_name and folder_name? Would I not have to loop through and create lists of all of those names before manipulating them? I tried running the code above as is and it did not work. If you could explain in more detail I would appreciate it.
Typo fixed. Why shouldn't you rename the files at once?
Thanks, now I'm getting an error saying `for folder_name in glob.glob(sys.argv[1]): IndexError: list index out of range. Any ideas?
for folder_name in os.listdir("."): if folder_name != 'boyaakaa.py' :
^ I changed glob.glob(sys.argv[1]) to os.listdir("."): and added the one if statement so the program doesnt try to edit the .py script and it worked no problems, thanks Dan ya da man
1

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

2 Comments

Is that like pathlib for 2.x?
@Kevin: Similar. It works in both 2.x and 3.x, and subclasses bytes/str/unicode.

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.