【问题标题】:read multiple files and save to xls in columns (pypdf2 and xlsxwriterr读取多个文件并在列中保存到 xls(pypdf2 和 xlsxwriterr
【发布时间】:2021-07-16 19:17:51
【问题描述】:

我需要获取一个包含多个 PDF 的目录并将其结构化为 xls

但我不明白如何在目录中制作列表将数据保存在xls中

enter import PyPDF2
    import xlsxwriter
#---------------------Input file-----------------------------------#
pdf_file = open('arquivo_file','rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
page = read_pdf.getPage(0)
doc = read_pdf.getOutlines
page_content = page.extractText()
text = page_content.replace("\n", " ").replace("\t", " ").replace("  ", "")
content = page_content.split("\n")
data = content[0]
worksheet.write(1, 1, data)
workbook.close() here

【问题讨论】:

  • 请先用平面英文写下你的逻辑,作为你需要执行的步骤。然后谷歌每一步。通常,您可能会惊讶于您的问题没有必要在 SO 上提问,而是将其分解为更小的步骤并为它们查找答案。
  • 读取多个文件:表示先读取单个文件。然后循环读取这些文件。
  • 在列中保存到 xls:搜索您可以在 python 中使用哪些库来保存到 excel 文件。如果您使用的是xlsxwriter,那就太好了。但是你检查过你有什么选择吗?你试过openpyxl吗?还是pandas
  • “我需要一个包含多个 PDF 的目录”:所以你需要一个目录中这些 PDF 文件的列表。您是否在 google 上尝试过不同的搜索查询?试试这个:“获取python目录中的文件列表”.
  • 提示:您需要import os; os.listdir(DIRPATH)import glob; glob.glob(DIRPATH)

标签: python excel pdf pypdf2 xmlwriter


【解决方案1】:

您的代码通常类似于这样。

import os
import glob

DIRPATH = "/path/to/your/pdf/directory"

# Get list of files with extension .pdf in a given directory
pdf_filepaths = glob.glob(os.path.join(DIRPATH, '*.pdf'))

# Loop over the pdf file-paths
# For each pdf-file:
#   1. read each pdf file
#   2. process the content you read (optional)
#   3. save the processed content to excel file
for i, pdf_filepath in enumerate(pdf_filepaths):
    content = read_pdf_file(pdf_filepath)
    content = process_data(content)
    write_excel_file(filename='out_{i}.xlsx', content=content)

在这里,我假设您将读取、处理和写入逻辑包装在三个函数中:

def read_pdf_file(filepath):
   # your pdf reading logic goes here
   ...

   return content

def process_data(content):
   # your post-reading data-processing logic goes here
   ...

   return content

def write_excel_file(filepath, content):
   # your logic for writing to excel-file goes here
   ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2023-04-05
    相关资源
    最近更新 更多