Python - 将脚本添加到 select 所有 pdf 文件

Python - adding a script to select all pdf files

我正在尝试批量标记一些 pdf 文件,我在 github 上发现了一些非常相似的东西,但你必须在脚本中命名每个文件以匹配它的实际 pdf 文件上班。

https://github.com/iprapas/pythonpdf

def stamp_pdf(input_path, stamp_path, output_path, add_frame=False):
    output = PdfFileWriter()
    create_pdf_stamp(stamp_path, add_frame=add_frame)
    pdf_in = PdfFileReader(open(input_path, 'rb'))
    pdf_stamp = PdfFileReader(open(stamp_path, 'rb'))
    stamp = pdf_stamp.getPage(0)

    for i in xrange(pdf_in.getNumPages()):
        page = pdf_in.getPage(i)
        page.mergePage(stamp)
        output.addPage(page)

    with open(output_path, 'wb') as f:
        output.write(f)

def main():
    stamp_pdf('../input/input1.pdf', '../temp/tmp_stamp.pdf', '../output/stamped1.pdf')
    stamp_pdf('../input/input1.pdf', '../temp/tmp_stamp.pdf', '../output/stamped1_with_frame.pdf', add_frame=True)
    stamp_pdf('../input/input2.pdf', '../temp/tmp_stamp.pdf', '../output/stamped2.pdf')
    stamp_pdf('../input/input2.pdf', '../temp/tmp_stamp.pdf', '../output/stamped2_with_frame.pdf', add_frame=True)

if __name__ == "__main__":

main()

我确定有一种方法可以替换单个文件 link 以便它直接指向目录并保留文件名。任何帮助我入门的指示都将不胜感激,因为我一直在尝试各种代码,但运气不佳。

使用 pathlib

轻松访问和管理路径和文件名

示例:

from pathlib import Path

p = Path.cwd()
print(p)
>>> WindowsPath('E:/PythonProjects/DataCamp')

pdf_files = list(p.glob('*.pdf'))
print(pdf_files)
>>> [WindowsPath('E:/PythonProjects/DataCamp/aapl.pdf')]

pdf_name = pdf_files[0].name
print(pdf_name)
>>> 'aapl.pdf'
  • 使用glob方法查找所有pdf个文件,包括子目录,带**个通配符
    • p.glob('**/*.pdf')
  • 使用name获取并轻松跟踪文件名

输出文件:

out_dir = p / 'output'
print(out_dir)
>>> WindowsPath('E:/PythonProjects/DataCamp/output')

out_pdf = out_dir / f'stamped_{pdf_name}'
print(out_pdf)
>>> WindowsPath('E:/PythonProjects/DataCamp/output/stamped_aapl.pdf')

pythonpdf 库可能不适用于 pathlib 个对象:

  • 轻松将 pathlib 对象转换回 str
print(type(stamp_path))
>>> pathlib.WindowsPath

print(type(str(stamp_path))
>>> str

create_pdf_stamp(str(stamp_path), add_frame=add_frame)

遍历 .glob:

  • .glob 对象是生成器函数
p = Path('e:/PythonProjects')
files = p.glob('**/*.pdf')

for file in files:
    print(file)
    ...
    # do other stuff