I made a program that merges all the PDFs in a certain map. The program is made so it merges only one sided PDFs. I would like your opinion on the code and how can it be improved.

while True:
        map_name = input("Name of the map where PDFs are saved: ")    # map where your documents are 
        initial_path = r"C:\Users\...\Scanned Documents"              # the initial path where all your documents get saved
        path = os.path.join(initial_path, map_name)

    except (OSError, FileNotFoundError):
        print("There is no map with that name!")

PDF_name_input = input("Name of your merged PDF: ")
PDF_name = "{0}.pdf".format(PDF_name_input)

PDF_arr = []
for file in os.listdir("."):

    if file.endswith("pdf"):

merger = PyPDF2.PdfFileMerger()

for element in PDF_sez:
    merger.append(open(element, "rb"))

with open(PDF_name, "wb") as fout:

List Comprehension

PDF_arr can be made into a list with one line

PDF_arr = [file for file in os.listdir(".") if file.endswith("pdf")]


Personally, I would use f"" when formatting variables into strings. It allows you to directly place variables without having to call the .format() function on them.

PDF_name = f"{input('Name of your merged PDF: ')}.pdf"

I also moved the input into the string, saving line count. It's also another quirk f"" has.

  • \$\begingroup\$ Downvoter, please explain why you downvoted so I may improve my answer. \$\endgroup\$ – Linny Mar 17 '20 at 23:18
  • 2
    \$\begingroup\$ I didn't downvote, but I would really avoid anything more complex than variable references in an f-string. \$\endgroup\$ – l0b0 Mar 18 '20 at 2:22
  • 1
    \$\begingroup\$ Isn't this just low hanging fruit. I could get more from a linter. Also pushing f-strings when they're really new is just obnoxious to people that have to support more than one version of Python. \$\endgroup\$ – Peilonrayz Mar 18 '20 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.