我是Python新手,我想要的是在一个文件夹中批量保护一系列PDF文件,每个文件随机生成一个唯一的密码-这些文件名密码组合应该保存在某个地方(可能是CSV文件)
当前正在使用一个代码,该代码使用用户定义的相同密码保护文件夹中的所有文件。但我无法为每个PDF使用不同的自动生成密码来保护它们
事先非常感谢你的帮助
import os
import pikepdf
from pikepdf import Pdf
password = 'test'
path = 'path'
def protect(file, password=password):
pdf = Pdf.open(file)
pdf.save(os.path.splitext(file)[0] + '_encrypted.pdf',
encryption=pikepdf.Encryption(owner=password, user=password, R=4))
pdf.close()
return
def remove_originals(file):
if file.endswith(('.pdf', '.PDF')):
if not file.endswith('_encrypted.pdf'):
os.remove(file)
#protecting
for folder, subfolders, files in os.walk(path):
for file in files:
if file.endswith(('.pdf', '.PDF')):
protect(os.path.join(folder, file))
#removing originals
for folder, subfolders, files in os.walk(path):
for file in files:
if file.endswith(('.pdf', '.PDF')):
remove_originals(os.path.join(folder, file))
#renaming the encrypted files to match the original filenames
for folder, subfolders, files in os.walk(path):
for file in files:
if file.endswith(('.pdf', '.PDF')):
os.rename(os.path.join(folder, file), os.path.join(folder, file.replace('_encrypted', '')))
请参阅下面的代码,以获得每个pdf自动生成密码的所需输出:
在您的代码中实现:
代码:
如果您有任何问题,请告诉我:)
相关问题 更多 >
编程相关推荐