为什么做这个?
- 因为有时候我们需要打印,需要知道自己的总页数然后算钱。
- 如果有word,毕竟去打印店,转化为.pdf打印好些。
代码展示
pip install PyPDF2
from PyPDF2 import PdfFileReader as pr
import os
def single_pdf_count(pdf_path: str) -> int:
count = 0
try:
f = open(pdf_path, 'rb')
pdf = pr(f)
count += pdf.getNumPages()
f.close()
except:
print(pdf_path, '该文件出现异常,可能是权限问题或者被加密了')
return count
def folder_pdf_files(folder: str) -> list[str]:
file_list = []
for a, b, c in os.walk(folder):
for filename in c:
if filename[-3:].lower() == 'pdf':
file_path = os.path.join(a, filename)
file_list.append(file_path)
print(folder, ": 有", len(file_list), "个pdf文件")
return file_list
def folders_pdf_pages(folders: list[str]) -> int:
print("正在计算...")
pdf_files = []
for folder in folders:
pdf_files += folder_pdf_files(folder)
count = 0
for pdf_path in pdf_files:
count += single_pdf_count(pdf_path)
return count
if __name__ == '__main__':
folders_list = ["文件夹目录1", "文件夹目录2"]
pdf_count = folders_pdf_pages(folders_list)
print("总的页数:", pdf_count)