Search code examples
pythonpypdf

Python PyPDF2 merger doesn't let os.remove work


I can't figure out how to close the files I'm trying to delete in python. Code:

merger = PdfFileMerger()
for auth in newAuths:
    merger.append(auth)
merger.write(r"C:\stack\overflow.pdf")
for i in newAuths:
    os.remove(i)

Everything works until the last two lines of code. It returns: 'PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:' Curious how I can close merger from accessing a file?


Solution

  • The file is still open and being used by the merger the close() method of PdfFileMerger() will close the file and allow you to remove it.

    merger = PdfFileMerger()
    for auth in newAuths:
        merger.append(auth)
    merger.write(r"C:\stack\overflow.pdf")
    merger.close()
    for i in newAuths:
        os.remove(i)