搜集了一些PDF资料,要统计这些PDF资料每一个的页数,用python写了几行代码实现
import os
from PyPDF2 import PdfReader
def get_pdf_page_count(file_path):
try:
reader = PdfReader(file_path)
return len(reader.pages)
except Exception as e:
print(f"Error reading {file_path}: {e}")
return None
def list_pdfs_in_folder(folder_path):
# List all files in the folder and filter for PDF files
sumpage = 0
pdf_files = [f for f in os.listdir(folder_path) if f.endswith('.pdf')]
for pdf_file in pdf_files:
full_path = os.path.join(folder_path, pdf_file)
page_count = get_pdf_page_count(full_path)
if page_count is not None:
print(f" {pdf_file}, 页数: {page_count}")
sumpage = sumpage + page_count
print(sumpage)
# Specify the folder path
folder_path = "你的文件路径"
# List and print PDF files with their page count
list_pdfs_in_folder(folder_path)
输出结果: