0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

officeファイルやpdfファイルのページ数付きのファイルリストを作る。

Last updated at Posted at 2025-07-21

はじめに

Pythonで特定のフォルダのファイルリストをまとめる際、ファイルのパスやファイルサイズの取得はosモジュールを使えば簡単にできる。しかし、PDFファイル、エクセル、ワード、パワーポイントのページ数を取得するには、専用のモジュールを使う必要がある。この記事では、各ファイルのページ数を取得する方法についてまとめてみた。

目次

PDFファイルのページ数取得

pdfファイルのページ数取得はpypdfを使えばできる。
pypdf.PdfReader()でPDFファイルを読み出し。pdf.pagesでページ数を取得する。
pypdfは、PDFの色々な操作ができる。その他操作はPythonでPDFファイルの読み書きマージやパスワード解除したりする。を参照。

import pypdf
file_path = 'ファイルのパス'
pdf    = pypdf.PdfReader(file_path)
print(len(pdf.pages))

戻る

エクセルファイルのページ数取得

エクセルファイルはopenpyxlでページ数を取得できる。ただし、旧ファイルのxlsは取得できないのでwin32comを使う必要がある。各モジュールはpipで取得する。win32comは、xlsとxlsx両方にも対応している。ただ、win32comはLinuxでは使えないので注意。

pip install openpyxl
pip install pywin32
import openpyxl as px
import win32com.client # pip install pywin32

file_path = 'ファイルのパス'

#xlsxファイルの場合
xls = load_workbook(file_path, read_only=True)
print(len(xls.sheetnames))

#xlsファイルの場合
excel = win32com.client.Dispatch("Excel.Application")
xls = excel.Workbooks.Open(file_path)
print(xls.Sheets.Count)
xls.Close(SaveChanges=False)
excel.Quit()

戻る

ワードファイルのページ数取得

ワードファイルはpython-docxでページ数を取得できる。ただし、旧ファイルのdocは取得できないのでwin32comを使う必要がある。各モジュールはpipで取得する。win32comは、docとdocx両方対応している。そのため、わざわざpython-docxを使う必要はないかもしれない。ただ、win32comはLinuxでは使えないので注意。

pip install python-docx
pip install pywin32
from docx import Document #pip install python-docx
import win32com.client # pip install pywin32

file_path = 'ファイルのパス'

#docxファイルの場合
doc = Document(file_path)
print(len(doc.element.body.xpath('//w:secPr'))) #//w:secPrでページのセクション数を取得する

#docファイルの場合
word   = win32com.client.Dispatch("Word.Application")
doc    = word.Documents.Open(file_path)
print(doc.ComputeStatistics(2))  # 2 = wdStatisticPages
doc.Close(SaveChanges=False)
word.Quit()

戻る

パワーポイントファイルのページ数取得

パワーポイントファイルはpython-pptxでページ数を取得できる。ただし、旧ファイルのpptは取得できないのでwin32comを使う必要がある。各モジュールはpipで取得する。win32comは、pptとpptx両方対応しているの。パワーポイントをwin32comで実行する場合、バックグラウンドでファイルを開くことができない。一度ファイルを開く分、サイズ計測の時間が長くなる。計測対象がpptxだけなのであればpython-pptxの方が良いと思う。

pip install python-pptx
pip install pywin32
from pptx import Presentation #pip install python-pptx
import win32com.client # pip install pywin32

file_path = 'ファイルのパス'

#pptxファイルの場合
ppt = Presentation(file_path)
print(len(ppt.slides)

#pptファイルの場合
power  = win32com.client.Dispatch("PowerPoint.Application")
ppt    = power.Presentations.Open(file_path)
print(ppt.Slides.Count)
ppt.Close()
power.Quit()

戻る

ファイルリスト作成の例

最後に、特定のフォルダの"フォルダパス"、"ファイル名"、"ファイルのページ数"、"ファイルのサイズ"をエクセルファイルに出力する例を作ってみた。
関数get_page_count()で、拡張子別にファイルのページ数を取得している。ファイルのリンク付けにはopenpyxlを使っている。

import os
import re
import pandas as pd
import pypdf
from docx import Document #pip install python-docx
from pptx import Presentation #pip install python-pptx
import win32com.client # pip install pywin32
import openpyxl as px
from openpyxl import load_workbook
from openpyxl.styles import Font

def get_page_count(dir, file, ext):
	RetLen = 'None'
	
	try:
		file_path = os.path.join(dir,file)
		if ext in ['.pdf']:
			pdf    = pypdf.PdfReader(file_path)
			RetLen = len(pdf.pages)
		
		# 段落がある場合はこちらでも計測できる
		#elif ext in ['.docx']:
		#	doc    = Document(file_path)
		#	RetLen = len(doc.element.body.xpath('//w:secPr'))

		elif ext in ['.pptx']:
			ppt    = Presentation(file_path)
			RetLen = len(ppt.slides)
			
		elif ext in ['.xlsx','xlsm','.XLSM']:
			xls    = load_workbook(file_path, read_only=True)
			RetLen = len(xls.sheetnames)
			
		elif ext in ['.doc','.docx']:
			word   = win32com.client.Dispatch("Word.Application")
			doc    = word.Documents.Open(file_path)
			RetLen = doc.ComputeStatistics(2)  # 2 = wdStatisticPages
			doc.Close(SaveChanges=False)
			word.Quit()
			
		elif ext in ['.ppt']:
			power  = win32com.client.Dispatch("PowerPoint.Application")
			ppt    = power.Presentations.Open(file_path)
			RetLen = ppt.Slides.Count
			ppt.Close()
			power.Quit()
			
		elif ext in ['.xls']:
			excel = win32com.client.Dispatch("Excel.Application")
			xls = excel.Workbooks.Open(file_path)
			RetLen = xls.Sheets.Count
			xls.Close(SaveChanges=False)
			excel.Quit()
			
		else:
			RetLen = 'None'
		return RetLen
	
	except:
		print(sys.exc_info())
		RetLen = 'Error'
		return RetLen

def get_size_count(dir, file):
	try:
		return f'{os.path.getsize(os.path.join(dir,file))//1024:,}'
	except:
		print(sys.exc_info())
		return 'Error'

def main():
	file_dic={'フォルダパス':[],'フォルダLink':[],'ファイル':[],'拡張子':[],'ページ数':[],'サイズ(kB)':[]}
	# 現在フォルダからサブフォルダも再帰的に確認する
	for Dir, SubDirs, Files in os.walk(os.getcwd()):
		for f in Files:
			file_dic['フォルダパス'].append(Dir)
			file_dic['フォルダLink'].append('Link')
			file_dic['ファイル'].append(f)
			file,ext=os.path.splitext(f)
			file_dic['拡張子'].append(ext)
			file_dic['ページ数'].append(get_page_count(Dir,f,ext))
			file_dic['サイズ(kB)'].append(get_size_count(Dir,f))
	
	# データフレーム化
	df = pd.DataFrame(file_dic)
	
	# エクセル出力
	df.to_excel('リスト.xlsx',index=False)
	
	# リンクをつけるためopenpyxlで開く
	wb=px.load_workbook('リスト.xlsx')
	ws=wb.active
	
	# "フォルダパス"と"ファイル"の列にリンクをつける
	for cnt, (d,f) in enumerate(zip( df['フォルダパス'], df['ファイル']) ):
		
		#フォルダパスリンク
		cell = ws.cell(cnt+2,2)
		cell.hyperlink = f'{d}'
		cell.font = Font(color="0000FF", underline="single")
		
		#ファイルリンク
		cell = ws.cell(cnt+2,3)
		cell.hyperlink = f'{os.path.join(d,f)}'
		cell.font = Font(color="0000FF", underline="single")
	wb.save('リスト.xlsx')

if __name__=="__main__":
	main()


戻る

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?