Process a folder¶
Now put it all together. This script goes through every PDF in a folder, reports its page count, and keeps going if one file is broken:
from pathlib import Path
import ozaru
Path("broken.pdf").write_text("This is not a PDF.", encoding="utf-8")
for pdf in sorted(Path(".").glob("*.pdf")):
try:
pages = ozaru.page_count(pdf)
except ValueError:
print(f"{pdf.name}: skipped")
continue
print(f"{pdf.name}: {pages} pages")
Output:
Two details matter here:
continuemoves on to the next file, so one broken PDF doesn't stop the whole run.pdfis apathlib.Path, and ozaru accepts it directly, just like astr.
Use threads for large folders¶
ozaru releases Python's GIL while it reads a PDF, so several threads can work at
the same time. ThreadPoolExecutor is the simplest way to do that:
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import ozaru
pdfs = sorted(Path(".").glob("*.pdf"))
with ThreadPoolExecutor() as executor:
texts = executor.map(ozaru.extract_text, pdfs)
for pdf, text in zip(pdfs, texts):
print(f"{pdf.name}: {len(text)} characters")
Output:
executor.map returns the results in the same order as pdfs, so zip can pair
each file with its text.
That's the end of the tutorial. From here, the API reference has every detail in one place.