str*_*r14 4 python python-3.x pypdf2
def EncryptPDFFiles(password, directory):
pdfFiles = []
success = 0
# Get all PDF files from a directory
for folderName, subFolders, fileNames in os.walk(directory):
for fileName in fileNames:
if (fileName.endswith(".pdf")):
pdfFiles.append(os.path.join(folderName, fileName))
print("%s PDF documents found." % str(len(pdfFiles)))
# Create an encrypted version for each document
for pdf in pdfFiles:
# Copy old PDF into a new PDF object
pdfFile = open(pdf,"rb")
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfFile.close()
# Encrypt the new PDF and save it
saveName = pdf.replace(".pdf",ENCRYPTION_TAG)
pdfWriter.encrypt(password)
newFile = open(saveName, "wb")
pdfWriter.write(newFile)
newFile.close()
print("%s saved to: %s" % (pdf, saveName))
# Verify the the encrypted PDF encrypted properly
encryptedPdfFile = open(saveName,"rb")
encryptedPdfReader = PyPDF2.PdfFileReader(encryptedPdfFile)
canDecrypt = encryptedPdfReader.decrypt(password)
encryptedPdfFile.close()
if (canDecrypt):
print("%s successfully encrypted." % (pdf))
send2trash.send2trash(pdf)
success += 1
print("%s of %s successfully encrypted." % (str(success),str(len(pdfFiles))))
Run Code Online (Sandbox Code Playgroud)
我正在关注 Pythons Automate the Boring Stuff 部分。我在复制 PDF 文档时遇到了一些问题,但截至目前,每次运行该程序时,我复制的 PDF 都是空白页。我新加密的 PDF 有正确数量的页面,但它们都是空白的(页面上没有内容)。我以前遇到过这种情况,但无法重新创建。我试过在关闭我的文件之前睡一觉。我不确定在 Python 中打开和关闭文件的最佳实践是什么。作为参考,我使用的是 Python3。
小智 5
尝试将 pdfFile.close 移动到 for 循环的最后。
for pdf in pdfFiles:
#
# {stuff}
#
if (canDecrypt):
print("%s successfully encrypted." % (pdf))
send2trash.send2trash(pdf)
success += 1
pdfFile.close()
Run Code Online (Sandbox Code Playgroud)
思路是pdfWriter最后写出来的时候pdfFile需要可用并打开,否则无法访问页面写入新文件。
| 归档时间: |
|
| 查看次数: |
3886 次 |
| 最近记录: |