首页 > 解决方案 > 如何在pdfplumber中打开多个文件?

问题描述

我有多个使用 Access DB 表单创建的 PDF 文件。我可以从中提取文本的唯一方法是使用 pdfplumber。这是我的代码,它仅适用于 1 个文件。

import pdfplumber

with pdfplumber.open('CS_page_1.pdf') as pdf:
    page = pdf.pages[0]
    string = page.extract_text()
    file_name = string[43:48]
    print(file_name)

我需要使用这个提取的字符串来重命名这个文件和文件夹中的 100 个其他文件。最好的方法是什么?

标签: pythonpython-3.xfile-rename

解决方案


首先使用 glob ( https://docs.python.org/3/library/glob.html ) 构建文件夹中所有 pdf 的列表。

然后遍历它们中的每一个 - pdfplumb 它们以获得所需的字符串(您要将文件重命名为) - 然后单独重命名每个(https://www.tutorialspoint.com/python/os_rename.htm)。像这样的东西:

import glob
import pdfplumber
import os

arr_of_files = (glob.glob("/path/to/pdfs/*.pdf"))

for file in arr_of_files:
    with pdfplumber.open(file) as pdf:
        page = pdf.pages[0]
        string = page.extract_text()
        file_name = string[43:48]
        os.rename(file, file_name)
        

推荐阅读