This code basically already create the PDFs. After it created the PDF it is copied in its own folder. What I am trying to do is merge what is in the folder. Then it would go to the next folder and do the merge. Then on to the next folder and do the merge. And such. But when I do it, it's just merging the last PDF and not all the PDFs.
import os
import shutil
import time
from PyPDF2 import PdfFileMerger
from reportlab.pdfgen.canvas import Canvas
path = input("Paste the folder path of which all the PDFs are located to begin the automation.\n")
# Only allowed to use your C or H drive.
while True:
if "C" in path[0]:
break
elif "H" in path[0]:
break
else:
print("Sorry you can only use your C drive or H drive\n")
path = input("Paste the folder path of which all the PDFs are located to begin the automation.\n")
moving_path = path + "\\Script"
new_path = moving_path + "\\1"
folder_name = {}
# List all directories or files in the specific path
list_dir = ["040844_135208_3_192580_Sample_010.pdf", "040844_135208_3_192580_Sample_020.pdf",
"040844_135208_3_192580_Sample_050.pdf", "058900_84972_3_192163_Sample_010.pdf",
"058900_84972_3_192163_Sample_020.pdf", "058900_84972_3_192163_Sample_030.pdf"]
# Pauses the program
def wait(num):
time.sleep(num)
# Change and make directory
def directory():
os.chdir(path)
for i in list_dir:
canvas = Canvas(i)
canvas.drawString(72, 72, "Hello, World")
canvas.save()
os.makedirs("Script")
os.chdir(path + "\\Script")
os.makedirs("1")
os.makedirs("Merge")
os.chdir(new_path)
def main():
match = []
for i in list_dir:
search_zero = i.split("_")[2]
if search_zero != "0":
match.append((i.split("_", 3)[-1][:6]))
else:
match.append((i.split("_", 0)[-1][:6]))
new_match = []
for i, x in enumerate(match):
if "_" in match[i]:
new_match.append(x[:-1])
else:
new_match.append(x)
for i in list_dir:
key = i.split("_", 3)[-1][:6]
if key in folder_name:
folder_name[key].append(i)
else:
folder_name[key] = [i]
for i, x in enumerate(list_dir):
# Skips over the error that states that you can't make duplicate folder name
try:
os.makedirs((new_match[i]))
except FileExistsError:
pass
# Moves the file that doesn't contain "PDFs" into the "1" folder and the one that does in the "Merge" folder
if "PDFs" not in list_dir[i]:
shutil.copy(f"{path}\\{list_dir[i]}", f"{new_path}\\{new_match[i]}")
os.chdir(f"{new_path}\\{new_match[i]}")
merger = PdfFileMerger(x)
merger.append(x)
merger.write(f"{new_match[i]}.pdf")
merger.close()
os.chdir(new_path)
else:
shutil.copy(f"{path}\\{list_dir[i]}", f"{moving_path}\\Merge\\{x}")
directory()
wait(0.7)
main()
print("Done!")
wait(2)