python 统计pdf页数
import os
import PyPDF2
import sys, jm, traceback
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QAction
from PyQt5 import QtCore, QtGui, QtWidgets
def get_all_file_by_type(path, type=(), get_all_dirs = True): # 获得以type类型结尾的所有文件,返回一个list

filelist = []for a, b, c in os.walk(path):for name in c:fname = os.path.join(a, name)if fname.endswith(type):filelist.append(fname)if not get_all_dirs:# 仅在当前目录查找文件print("跳出循环")breakprint("总共有%d个文件"%filelist.__len__())return filelist

def output_log(outpath, message):
with open(outpath, ‘a’) as f:
f.write(message)

def compute_pdfpage(path_bc, path, get_all_dirs = False):
counts = 0
type = (“PDF”,“pdf”)
file_list = get_all_file_by_type(path=path, type=type, get_all_dirs = get_all_dirs)
jd_pj = 100 / len(file_list)
jd = 100 / len(file_list)
for pdf in file_list:
try:
reader = PyPDF2.PdfFileReader(pdf)
# 不解密可能会报错:PyPDF2.utils.PdfReadError: File has not been decrypted
if reader.isEncrypted:
reader.decrypt(‘’)
page_num = reader.getNumPages()
print(pdf, page_num)
counts += page_num
output_log(path_bc, ‘%s %s\n’%(pdf, page_num))
self.textEdit.append(‘%s %s’%(pdf, page_num))
except Exception as e:
print(“-”*70)
print(pdf + “该文件出现异常,可能是权限问题”)
print(e)
print(“-”*70)
self.textEdit.append(pdf + “该文件出现异常,可能是权限问题”)
self.progressBar.setProperty(“value”, jd)
QApplication.processEvents()
jd = jd + jd_pj
os.startfile(path_bc)
return counts

def main(self):
def askdirectory_pdfhb_xz():
“”“”“”
_translate = QtCore.QCoreApplication.translate
folder = QFileDialog.getExistingDirectory()
self.lineEdit.setText(_translate(“Form”, folder))
def askdirectory_pdfhb_xz1():
“”“”“”
_translate = QtCore.QCoreApplication.translate
folder = QFileDialog.getExistingDirectory()
self.lineEdit_2.setText(_translate(“Form”, os.path.join(folder, ‘统计表.txt’)))
def ye_main():
try:
path = self.lineEdit.text()
path_bc = self.lineEdit_2.text()
counts = compute_pdfpage(path_bc, path, get_all_dirs=True)
print(“总共%d页” % counts)
except:
self.textEdit.append(‘出错了\n%s’ % traceback.format_exc())
self.pushButton.clicked.connect(ye_main)
self.toolButton.clicked.connect(askdirectory_pdfhb_xz)
self.toolButton_2.clicked.connect(askdirectory_pdfhb_xz1)

if name == ‘main’:
if name == ‘main’:
app = QApplication(sys.argv)
MainWindow = QMainWindow() # QMainWindow模块名
self = jm.Ui_MainWindow()
self.setupUi(MainWindow)
main(self)

MainWindow.show()sys.exit(app.exec_())