Nov-24-2019, 05:23 AM
The if statement on line 23 is there because of the uncaught exceptions, I wanted to suppress the exception text and go straight to the else on line 26
import argparse, os, pdftitle, re parser = argparse.ArgumentParser(description='Generate filenames from PDF titles.') parser.add_argument('path', help='Starting folder path') parser.add_argument('-r', '--rename', action='store_true', help='Rename files (otherwise just display)') args = parser.parse_args() def pdf_recurse(SrcFolder): for FileName in os.listdir(SrcFolder): FilePath = SrcFolder + '\\' + FileName if os.path.isdir(FilePath): pdf_recurse(FilePath) else: FileExt = FilePath[-3:] if FileExt.lower() == 'pdf': PdfTitle = "" try: PdfTitle = pdftitle.run(FilePath) except: print(FilePath) print("an exception occurred") if PdfTitle == "" or PdfTitle == 1: print(FilePath) print("Could not read") else: NewName = new_name(PdfTitle, FileName) if NewName != "" and NewName != FileName: print(FilePath) print(NewName) if args.rename: os.rename(r'' + str(FilePath), r'' + SrcFolder + '\\' + NewName) def new_name(ReadTitle, FileName): if len(ReadTitle) < 6: return "" Match = re.search('(iptc|spe)[\s\-]{0,1}[0-9]+' , FileName, re.IGNORECASE) if Match != None: return "" if len(ReadTitle) > 72: ReadTitle = ReadTitle[:72] NewName = re.sub('[^\w_.)( -]', '', ReadTitle) + '.pdf' return NewName pdf_recurse(args.path)