FShiwani
FShiwani

Reputation: 181

Append an incrementing number to files of same name

I have written some python code that will rename all files in the current directory to 5 characters long. I'm trying to improve it now by checking if a file of the same name already exists then I append an incrementing number onto the name.

For example, If a directory contains program_a.c and program_b.c. If I were to run my current program, it would shorten both to 5 characters long - progr.c and progr.c which isn't desirable. Instead I'm trying to get the output like this - progr1.c and progr2.c. I'm not too sure what the easiest is to go about doing this.

#!/usr/bin/python3
import sys, os

cwd = os.getcwd()

for FILE in os.listdir(cwd):
    base, ext = os.path.splitext(FILE)
    if len(base) > 5:
        new_base = base[0:5]
        count = 0
        for n_FILE in os.listdir(cwd):
            n_base, n_ext = os.path.splitext(n_FILE)
            if n_base == new_base:
                count += 1
                new_base + str(count)

        os.rename(cwd+"/"+FILE, cwd+"/"+new_base+ext)
        count = 0

Upvotes: 0

Views: 396

Answers (1)

TLOwater
TLOwater

Reputation: 638

You could write the used file paths to a dictionary with the value of each key being the number of times it's seen. Then if you make the same abbreviation you can use the value + 1 for the given file path as the number to append.

For example:

#!/usr/bin/python3
import sys, os

cwd = os.getcwd()
files_used = {}


for FILE in os.listdir(cwd):
    base, ext = os.path.splitext(FILE)
    if len(base) > 5:
        new_base = base[0:5]
        if new_base in files_used:
            files_used[new_base] += 1
        else:
            files_used[new_base] = 1
        os.rename(cwd + "/" + FILE, cwd + "/" + new_base + str(files_used[new_base]) + ext)
    else:
        base, ext = os.path.splitext(FILE)
        if new_base in files_used:
            files_used[new_base] += 1
        else:
            files_used[new_base] = 1
        os.rename(cwd + "/" + FILE, cwd + "/" + new_base + str(files_used[new_base]) + ext)

Upvotes: 3

Related Questions