I want to batch rename a set of files in a folder with specific conditions, which is (add prefix, start from a specific number and increase in +1 series, skip a specific number in the series, add files with same number using an underscore)

I have a set of scanned document files, starting from a specif number let's say 10 and increments with 1. Ex 10,11,12,...

.But some files will be missing for ex maybe 13 will be missing, so need an option to skip that 13 and start with 14. Also some documents will be 2 pages, so need to put underscore to distinguish. For ex 15th document is 2 pages, so need to put 15_2 for the second file.

UPDATE1: I have fixed almost everything, now its working perfectly, but now i need to do two things 1. Need a while loop to check whether the entered number for skip is less than or equal to x.

  1. I have no idea on how to do the below condtion:

Also some documents will be 2 pages, so need to put underscore to distinguish. For ex 15th document is 2 pages, so need to put 15_2 for the second file.

UPDATE 2 : I have added the condition for when there in repeated files but syntax error as below UPDATE 3 : My friend helped me to get rid of the syntax error.

UPDATE 4 : My friend helped with some logic and i have solved the puzzle, updated here for reference. Thank you Jishnu

line 20
i -= 1 and dst = pre.upper() + str(i) + "_2.pdf"
import os

pre = str(input("Enter prefix : "))

while pre not in ("cin", "CIN", "CRT", "crt", "inv", "INV", "DO", "do"):
    pre = str(input("Please check the entered prefix and try again : "))

x = int(input("Enter first no : "))
skip = int(input("Skip : "))
rt = int(input("Enter repeating number"))
rt = rt + 1
def main():
    i = x


    for filename in os.listdir("C:/Users/Ajeshhome/Desktop/scan/"):
        if skip == i:
            i += 1
            dst = pre.upper() + str(i) + ".pdf"
            src = 'C:/Users/Ajeshhome/Desktop/scan/' + filename
            dst = 'C:/Users/Ajeshhome/Desktop/scan/' + dst
            os.rename(src, dst)
            i += 1

        elif rt == i:
            dst = pre.upper() + str(i-1) + "_2.pdf"
            src = 'C:/Users/Ajeshhome/Desktop/scan/' + filename
            dst = 'C:/Users/Ajeshhome/Desktop/scan/' + dst
            os.rename(src, dst)
            i += 1
        else:
            dst = pre.upper() + str(i) + ".pdf"
            src = 'C:/Users/Ajeshhome/Desktop/scan/' + filename
            dst = 'C:/Users/Ajeshhome/Desktop/scan/' + dst
            os.rename(src, dst)
            i += 1

def lis():

        path = 'C:/Users/Ajeshhome/Desktop/scan/'

        files = []
        # r=root, d=directories, f = files
        for r, d, f in os.walk(path):
            for file in f:
                if '.pdf' in file:
                    files.append(os.path.join(r, file))

        for f in files:
            print(f)






# Driver Code
if __name__ == '__main__':
    # Calling main() function
    main()
    lis()
    os.system('pause')



1 Answers

0
Peter Sutton On Best Solutions

I'm not sure how to solve everything you're asking about. But here's a start: reliable prefix selection. Here's the whole code:

PREFIXES = {
    "CIN",
    "CRT",
    "DO",
    "INV",
}

def ask_prefix():
    prefixes = sorted(PREFIXES)
    for i, prefix in enumerate(prefixes, start=1):
        print(f'{i}) {prefix}')
    while True:
        reply = input('Select prefix: ').strip().upper()
        try:
            index = int(reply) - 1
        except ValueError:
            if reply in PREFIXES:
                return reply
        else:
            if 0 <= index < len(prefixes):
                return prefixes[index]
        print(f'{reply!r} is not a valid prefix.')

pre = ask_prefix()

A global set for all valid prefixes:

PREFIXES = {
    "CIN",
    "CRT",
    "DO",
    "INV",
}

Now let's look at ask_prefix(). The first line creates a sorted list from the PREFIXES so they print out in a nice order. Then:

for i, prefix in enumerate(prefixes, start=1):
    print(f'{i}) {prefix}')

Use enumerate to number the prefixes then print out the number and prefix to create a menu. Next, enter an infinite loop (while True:), which only breaks when the user enters or selects a valid prefix.

Ask the user for a prefix or a number from the menu and clean up the input:

reply = input('Select prefix: ').strip().upper()

Try the reply as an index:

try:
    index = int(reply) - 1
except ValueError:
    ...
else:
    if 0 <= index < len(prefixes):
        return prefixes[index]

If it doesn't work as an index, try it as a prefix:

if reply in PREFIXES:
    return reply