How to rewrite the file that Python is currently reading

I'm not too sure that this is the best way to talk about this, but what I want to do is read the pdf file, make various modifications and save the modified pdf file compared to the original file. At the moment, I can save the modified pdf file to a separate file, but I'm looking to replace the original, and 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 outputStreamto a different file name, it works fine, I just can't save the input file because it is still in use. I tried to .close()stream, but it also gave me errors.

I have a feeling that this one has a pretty simple solution, I just had no luck finding it.

Thank!

+3
3

, () , ? PdfFileReader, . .

from pyPdf import PdfFileWriter, PdfFileReader

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

...

del input # PdfFileReader won't mess with the stream anymore
inputStream.close()
del blank
blankStream.close()

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

:

import os
f = open('input.pdf', 'rb')
# do stuff to temp.pdf
f.close()
os.rename('temp.pdf', 'input.pdf')
+7

If the PDF files are small enough (it will depend on your platform), you can just read it all, close the file, change the data, and then write it all to one file.

+1
source

Source: https://habr.com/ru/post/1743553/


All Articles