Search code examples
pythonfilenamesprepend

Rename files in a directory with incremental index


INPUT: I want to add increasing numbers to file names in a directory sorted by date. For example, add "01_", "02_", "03_"...to these files below.

test1.txt (oldest text file)
test2.txt
test3.txt
test4.txt (newest text file)

Here's the code so far. I can get the file names, but each character in the file name seems to be it's own item in a list.

import os
for file in os.listdir("/Users/Admin/Documents/Test"):
if file.endswith(".txt"):
      print(file)

The EXPECTED results are:

   01_test1.txt
   02_test2.txt
   03_test3.txt
   04_test4.txt

with test1 being the oldest and test 4 being the newest.

How do I add a 01_, 02_, 03_, 04_ to each file name?

I've tried something like this. But it adds a '01_' to every single character in the file name.

new_test_names = ['01_'.format(i) for i in file]
print (new_test_names)

Solution

    1. If you want to number your files by age, you'll need to sort them first. You call sorted and pass a key parameter. The function os.path.getmtime will sort in ascending order of age (oldest to latest).

    2. Use glob.glob to get all text files in a given directory. It is not recursive as of now, but a recursive extension is a minimal addition if you are using python3.

    3. Use str.zfill to strings of the form 0x_

    4. Use os.rename to rename your files

    import glob
    import os
    
    sorted_files = sorted(
        glob.glob('path/to/your/directory/*.txt'), key=os.path.getmtime)
    
    for i, f in enumerate(sorted_files, 1):
        try:
            head, tail = os.path.split(f)            
            os.rename(f, os.path.join(head, str(i).zfill(2) + '_' + tail))
        except OSError:
            print('Invalid operation')
    

    It always helps to make a check using try-except, to catch any errors that shouldn't be occurring.