Search code examples
pythonmodulepypdf

Python: "import as" Keyword Error


I've been using Python and I'm importing the PyPDF2 module. I've actually figured how to make my problem work but I would like to know why my previous code was not working.

Here is the old code:

from PyPDF2 import PdfFileMerger as merger, PdfFileReader 

def MakeOne(filesList):


    for file in filesList:
        merger().append((file))
    merger().write("AllInOne.pdf")

    print("File AllInOne.pdf has been created")

This is the current code which now works.

from PyPDF2 import PdfFileMerger, PdfFileReader
def MakeOne(filesList):

    merger = PdfFileMerger()
    for file in filesList:
        merger.append((file))

    merger.write("AllInOne.pdf")

    print("File AllInOne.pdf has been created")

The first piece of code did not crash the console - in fact it did create a file. The only problem was that the file it created was not openable and was only 1 KB large. The second piece of code is similar to how many people have used this module in StackOverflow and it works perfectly. My question is: why did the first piece of code not provide me with the expected result given that I seemingly worked with "merger" correctly after importing PdfFileMerger as merger?

Thank you for any help provided!


Solution

  • As the previous comment notes, every time you call merger(), you're creating a new PdfFileMerger object. So, when you call merger().write("AllInOne.pdf"), you are writing a PDF which has no appended files.

    When you use import <module> as, you are ''aliasing'' the imported module. So your first code block is exactly the same as the following:

    from PyPDF2 import PdfFileMerger, PdfFileReader 
    
    def MakeOne(filesList):
    
    
        for file in filesList:
            PdfFileMerger().append((file))
        PdfFileMerger().write("AllInOne.pdf")
    
        print("File AllInOne.pdf has been created")