【问题标题】:Using Python to pull the number of pages in all the pdf documents in a directory使用Python拉取一个目录下所有pdf文档的页数
【发布时间】:2017-03-17 14:05:03
【问题描述】:

我正在尝试使用 PyPDF2 来获取目录中每个 pdf 的页数。我可以使用 .getNumPages() 来查找一个 pdf 文件中的页数,但我需要遍历一个目录并获取每个文件的页数。有什么想法吗?

这是我目前的代码:

import pandas as pd
import os
from PyPDF2 import PdfFileReader
df = pd.DataFrame(columns=['fileName', 'fileLocation', 'pageNumber'])
pdf=PdfFileReader(open('path/to/file.pdf','rb'))
for root, dirs, files in os.walk(r'Directory path'):
    for file in files:
        if file.endswith(".pdf"):
            df2 = pd.DataFrame([[file, os.path.join(root,file),pdf.getNumPages()]], columns=['fileName', 'fileLocation', 'pageNumber'])
            df = df.append(df2, ignore_index=True)

此代码只会将目录中第一个 PDF 文件的页数添加到数据框中。如果我尝试向 PdfFilereader() 添加目录路径,我会得到一个

PermissionError:[Errno 13] Permission denied.

【问题讨论】:

  • 您是否尝试过自己先做这件事?如果是这样,您应该发布您的代码,然后寻求帮助。 StackOverflow 不是让人们为您工作的地方!
  • mrpopo 我很欣赏 SO 的这一方面,但他只需要两行代码,所以也许我们可以破例:)
  • 我是 StackOverflow 的新手!我编辑了我的帖子并添加了我的代码。
  • 尝试用“f”替换“file”。我不认为它导致了问题,但它是一个 python 保留字。

标签: python pdf


【解决方案1】:

是的,使用

import glob
list_of_pdf_filenames = glob.glob('*pdf')

返回目录中所有 PDF 文件名的列表。

**编辑:**

通过将 open() 语句放在循环中,我可以让这段代码在我的计算机上运行:

import pandas as pd
import os
from PyPDF2 import PdfFileReader
df = pd.DataFrame(columns=['fileName', 'fileLocation', 'pageNumber'])
for root, dirs, files in os.walk(r'/home/benjamin/docs/'):
    for f in files:
        if f.endswith(".pdf"):
            pdf=PdfFileReader(open(os.path.join(root, f),'rb'))
            df2 = pd.DataFrame([[f, os.path.join(root,f), pdf.getNumPages()]], columns=['fileName', 'fileLocation', 'pageNumber'])
            df = df.append(df2, ignore_index=True)
print(df.head)

【讨论】:

  • 感谢您的帮助!我可以在目录中找到所有 PDF 文件名的列表没有问题。我无法在目录中找到这些 PDF 文件的页数。
  • @Dillanm 这就是我一直在使用的。我似乎无法弄清楚如何使用它并遍历目录以获取每个 PDF 文件的页数。
  • @Zfrieden 您用于“目录路径”的实际值是多少?而且,如果您暂时将最后两行注释掉,而只写print(root, file),它会打印什么?
  • @Benjamin '目录路径'是我桌面上本地文件夹的路径。如果我 print(root,file) 输出是文件夹中带有文件路径的每个文件名。
  • 为什么open() 语句不在循环内?我认为您可能希望单独打开每个 PDF 以阅读其页码,对吗?
【解决方案2】:

第 1 步:-

pip 安装 pyPDF2

第 2 步:-

import requests, PyPDF2, io
url = 'sample.pdf' 
response = requests.get(url)
with io.BytesIO(response.content) as open_pdf_file:
  read_pdf = PyPDF2.PdfFileReader(open_pdf_file)
  num_pages = read_pdf.getNumPages()
  print(num_pages)

【讨论】:

    猜你喜欢
    • 2016-10-20
    • 2013-12-31
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2011-05-10
    • 1970-01-01
    相关资源
    最近更新 更多