How do I overwrite a file currently being read by Python

Posted by Brian on Stack Overflow See other posts from Stack Overflow or by Brian
Published on 2010-04-30T18:27:06Z Indexed on 2010/04/30 18:27 UTC
Read the original article Hit count: 324

Filed under:
|
|
|
|

Hi guys,

I am not too sure the best way to word this, but what I want to do, is read a pdf file, make various modifications, and save the modified pdf over the original file. As of now, I am able to save the modified pdf to a separate file, but I am looking to replace the original, not create a new file.

Here is my current code:

from pyPdf import PdfFileWriter, PdfFileReader

output = PdfFileWriter()
input = PdfFileReader(file('input.pdf', 'rb'))
blank = PdfFileReader(file('C:\\BLANK.pdf', 'rb'))

# Copy the input pdf to the output.
for page in range(int(input.getNumPages())):
    output.addPage(input.getPage(page))

# Add a blank page if needed.
if (input.getNumPages() % 2 != 0):
    output.addPage(blank.getPage(0))

# Write the output to pdf.
outputStream = file('input.pdf', 'wb')
output.write(outputStream)
outputStream.close()

If i change the outputStream to a different file name, it works fine, I just cant save over the input file because it is still being used. I have tried to .close() the stream, but it was giving me errors as well.

I have a feeling this has a fairly simple solution, I just haven't had any luck finding it.

Thanks!

© Stack Overflow or respective owner

Related posts about python

Related posts about input