I'm trying to write a program in python that takes a PDF file and appends to it first any pdf which includes the name of a fruit to it(Mango, Orange or Apple), then appends the pdf's with the names of animals to the original file(Zebra, Monkey, Dog) and finally appends any remaining PDF's. This is the code I have:
import os
from PyPDF2 import PdfFileReader, PdfFileMerger
originalFile="C:/originalFile.pdf"
merger = PdfFileMerger()
merger.append(PdfFileReader(file(originalFile, 'rb')))
os.remove(originalFile)
for filename in os.listdir('C:/'):
if "Mango" in filename or "Apple" in filename or "Orange" in filename:
if ".pdf" in filename:
merger.append(PdfFileReader(file('C:/'+filename, 'rb')))
os.remove("C:/"+filename)
for filename in os.listdir('C:/'):
if "Zebra" in filename or "Monkey" in filename or "Dog" in filename:
if ".pdf" in filename:
merger.append(PdfFileReader(file('C:/'+filename, 'rb')))
os.remove("C:/"+filename)
for filename in os.listdir('C:/'):
if ".pdf" in filename:
merger.append(PdfFileReader(file('C:/TRIAL/'+filename, 'rb')))
os.remove("C:/TRIAL/"+filename)
merger.write(originalFile)
When I run this program I get the following Error:
os.remove(originalFile) WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'C:/originalFile.pdf'
Could anyone explain me how to close the file after I've added it to my merger file?