This is a sample code to create a docx file with thumbnails of JPEG files included in subfolders of a folder using the python-docx library and the free software "Reduction only." In Python 3.8.
I will describe it as a reference for python-docx, subprocess, etc. for myself someday.
import docx
import subprocess
from pathlib import Path
rootpath = Path(r"<The path of the folder that collects the photo folders>")
shukusenpath = Path(r"<For reduction only. Path>")
thumbdirname = "thumb" #For reduction only. The name of the subfolder specified in
for folderpath in rootpath.glob("*"):
if not folderpath.is_dir():
continue
newfilepath = rootpath / (folderpath.stem + ".docx")
if newfilepath.is_file():
continue
thumbpath = folderpath / thumbdirname
#Paste JPEG only
#Edit here if you want to paste other extensions as well.
picpaths = list(folderpath.glob("*.jpg "))
if len(picpaths) == 0:
continue
subprocess.run([shukusenpath, *picpaths])
doc = docx.Document()
for picpath in picpaths:
thumbpicpath = thumbpath / picpath.name
try:
doc.add_picture(str(thumbpicpath))
doc.add_paragraph()
doc.add_page_break()
except Exception:
pass
doc.save(newfilepath)
--python-docx
can be installed with pip install python-docx
.
--pathlib.Path
can combine paths with the/
operator.
--subprocess
starts the executable file and waits for the end by giving the executable file and a list of arguments as the first argument.
--To create a list with literal and expanded lists and generators as elements, use [literal, * list, * generator]
. *
is a list or generator expansion.
--If you give pathlib.Path
directly to docx.Document.add_picture
, an error will occur. This can be avoided by converting it to a string with str (pathlib.Path)
.
--In pathlib.Path
, stem
does not require parentheses, but in normal usage, ʻis_dir () requires parentheses. ʻIs_dir
does not result in an error, but it returns the method itself, so giving it to ʻif` is always true.
Recommended Posts