【问题标题】:Iterate Over Files (PDFs) to Run a Function迭代文件 (PDF) 以运行函数
【发布时间】:2020-06-23 16:26:49
【问题描述】:

我正在尝试从目录 (path) 中读取 PDF 文件,以从每个 PDF 中提取单个图像并写入同一目录。但是,我无法对每个文件执行以下功能,因为我的脚本只解析目录中的最后一个文件。我正在使用的代码如下所示:

pip install pymupdf

import os
import PyPDF2
import fitz  # from pymupdf
import glob


path = "C:\\Users\\mdl518\\Desktop\\"

def pdf_extract():
    for filename in glob.glob(os.path.join(path, "*.pdf"), recursive=True):  # file path specifying the location of the PDF files
        with open(os.path.join(os.getcwd(), filename),'rb') as f: # open/read the PDF files
            pdf_document=fitz.open(filename)
            for current_page in range(len(pdf_document)): # iterate over the total number of pages in each PDF
                for image in pdf_document.getPageImageList(current_page):
                    xref=image[0]  # initiates the cross-reference number for objects on the first page of the PDF
                    pix=fitz.Pixmap(pdf_document, xref)
                    if pix.n < 5:  # capture all images and write to the file path
                        pix.writeImage(os.path.join(path,"page%s-%s.jpg") % (current_page, xref))
                    else:
                        pix1 = fitz.Pixmap(fitz.csRGB, pix)
                        pix1.writeImage(os.path.join(path,"page%s-%s.jpg") % (current_page, xref))
                        pix1 = None
                    pix = None

pdf_extract()

我曾尝试使用globos.listdir()os.walk() 来解析单个 PDF,但我得到的最好的方法是从最后一个 PDF 文件中提取图像以读取/写入文件路径.有没有更简单的方法来解决这个问题,或者它只是对我的“glob”声明的一个小调整?非常感谢任何帮助!

【问题讨论】:

    标签: python loops automation directory pdf-parsing


    【解决方案1】:

    有两个问题

    1. with open(os.path.join(os.getcwd(), filename),'rb') as f: # open/read the PDF files 不需要,f 从未使用过
    2. 主要问题是您正在覆盖每个文件的图像
      • pix.writeImage(os.path.join(path,"page%s-%s.jpg") % (current_page, xref))
      • pix1.writeImage(os.path.join(path,"page%s-%s.jpg") % (current_page, xref))
      • current_page & xref 不一定对每个文件都是唯一的

    更新

    1. 代码使用标准库的一部分pathlib 进行了更新,因为它将路径视为带有方法的对象,而globos 将路径视为字符串。另见Python 3's pathlib Module: Taming the File System
    2. _{file.stem}添加到保存路径,以创建唯一的文件名
    3. 使用f-strings 进行字符串格式化。另见PEP 498 - Literal String Interpolation
    from pathlib import Path
    import PyPDF2
    import fitz
    
    def pdf_extract(path_to_files: str):
        
        path_to_files = Path(path_to_files)  # convert the str to a pathlib object
        
        for file in path_to_files.rglob('*.pdf'):  # pathlib has rglob
            pdf = fitz.open(file)
            for current_page in range(len(pdf)):
                for image in pdf.getPageImageList(current_page):
                    xref = image[0] 
                    pix = fitz.Pixmap(pdf, xref)
                    if pix.n < 5:
                        pix.writeImage(str(file.parent / f'page{current_page}-{xref}_{file.stem}.jpg'))  # updated filename
                    else:
                        pix1 = fitz.Pixmap(fitz.csRGB, pix)
                        pix1.writeImage(str(file.parent / f'page{current_page}-{xref}_{file.stem}.jpg'))  # updated filename
    
    
    # path to files
    path_to_files = r'C:\Users\mdl518\Desktop'  # do not include the trailing backslash '\'
    
    # call the function
    pdf_extract(path_to_files)
    

    【讨论】:

    • 再次感谢您对此功能的更新和更正,Trenton,脚本运行良好!我还尝试修改脚本以使用“os.mkdir(os.path.join(path,'Images'))”将输出图像写入文件路径中名为“Images”的子文件夹,特别是在之前添加此行行“for current_page in range(len(pdf))。但是,当我添加这个时,我现在收到错误“[WinError 183] 当该文件已存在时无法创建文件”。创建了子文件夹,但图像是写入主文件路径 - 您对编辑有什么建议吗?再次感谢!
    • 轻微更正 - 原始 PDF 的路径是 path_to_files,根据上述,而不是根据先前评论的路径。
    • @mdl518 目录已创建,但您尚未更新文件写入的位置,即pix.writeImagepix1.writeImage 这两行。路径应该以如下方式更新:str(file.parent / 'Images' / f'page{current_page}-{xref}_{file.stem}.jpg')
    • 谢谢,特伦顿,这成功了!我还添加了“return”行来关闭第二个“for”循环,以将所有提取的图像捕获到“Images”子文件夹,但该解决方案现在可以无缝运行。是否有其他文档可以推荐用于使用 file.parent 和 file.stem 自动命名各种文件类型?
    • @mdl518 只是答案中已有的链接。有一个指向 RealPython 文章和 pathlib 文档中的方法的链接。
    猜你喜欢
    • 2023-04-05
    • 2011-10-20
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2011-01-18
    相关资源
    最近更新 更多