简体   繁体   中英

Pypdf2 merger function and startswith

first time coder here. I'm trying to create a program to help automate some of my work in the office using python.

what I'm trying to do is to merge pdf file from Folder 1, with another pdf file from folder 2 with the same name. I also would like to use Tkinter gui

this is what I get so far

from tkinter import *
from PyPDF2 import PdfFileMerger

root = Tk()

  
# Creating a Label Widget
MainLabel = Label(root, text="PDF Rawat Jalan")
# Shoving it onto the screen
MainLabel.pack()

#Prompt Kode
KodeLabel = Label(root, text="Masukan Kode")
KodeLabel.pack()

#Input Kode

kode = Entry(root, bg="gray",)
kode.pack()


#function of Merge Button
def mergerclick():
    kode1 = kode.get()
    pdflocation_1 = "C:\\Users\\User\\Desktop\\PDF\\Folder 1\\1_"+kode1+".pdf"
    pdflocation_2 = "C:\\Users\\User\\Desktop\\PDF\\Folder 2\\2_"+kode1+".pdf"
    Output = "C:\\Users\\User\\Desktop\\PDF\\output\\"+kode1+".pdf"
    merger = PdfFileMerger()

    merger.append(pdflocation_1)
    merger.append(pdflocation_2)

    merger.write(open(Output, 'wb'))
    confirmation = kode1 +" merged"
    testlabel = Label(root, text=confirmation)
    testlabel.pack()



#Merge Button
mergerButton = Button(root, text= "Merge", command=mergerclick)
mergerButton.pack()

root.mainloop()

Now there is a third file i'm supposed to append, but the third file i'm supposed to append has date in its file name. for example: file 1 (010.pdf); file 2 (010.pdf); file 3 (010_2020_10_05).

There is like 9000 file per folder How I'm supposed to do this?

I think what you need is a way to just find files prefixed with a particular string. Based on the date suffix I'm guessing the file names may not be unique so I'm writing this to find all matches. Something like this will do that:

import pathlib

def find_prefix_matches(prefix):
  dir_path = pathlib.Path(directory_name)
  return [str(f_name) for f_name in dir_path.iterdir() 
      if str(f_name).startswith(prefix)]

If you are just learning to write code, this example is relatively simple. However it is not efficient if you need to match 9,000 files at the same time. To make it run faster you'll want to load the file list once instead of per request.

import pathlib

def find_prefix_matches(prefix, file_list):
  return [f for f in file_list if f.startswith(prefix)]

file_list = [str(f_name) for f_name in dir_path.iterdir()]
for file_name_prefix in your_list_of_files_to_append:
  file_matches = find_prefix_matches(file_name_prefix, file_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM