Create a docx file with thumbnails of photos in the folder pasted with the Python python-docx library and the free software "Reduction only."

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.

code

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)

Note

--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.

reference

Recommended Posts

Create a docx file with thumbnails of photos in the folder pasted with the Python python-docx library and the free software "Reduction only."
A memo organized by renaming the file names in the folder with python
Test & Debug Tips: Create a file of the specified size in Python
[Python] Get the files in a folder with Python
Create a Python image in Django without a dummy image file and test the image upload
[Python] Create a file & folder path specification screen with tkinter
Recursively get the Excel list in a specific folder with python and write it to Excel.
[Note] Import of a file in the parent directory in Python
Parse the Researchmap API in Python and automatically create a Word file for the achievement list
Process the contents of the file in order with a shell script
Output the contents of ~ .xlsx in the folder to HTML with Python
Specify or create a python folder and then save the screenshot.
Read a file in Python with a relative path from the program
The idea of feeding the config file with a python file instead of yaml
Dig the directory and create a list of directory paths + file names
Get a list of files in a folder with python without a path
Create a compatibility judgment program with the random module of python.
Create a binary file in Python
Replace the directory name and the file name in the directory together with a Linux command.
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
Create and edit spreadsheets in any folder on Google Drive with python
Receive a list of the results of parallel processing in Python with starmap
Open an Excel file in Python and color the map of Japan
Create a record with attachments in KINTONE using the Python requests module
I made a program to check the size of a file in Python
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
Check the existence of the file with python
[GPS] Create a kml file in Python
[Python] Precautions when finding the maximum and minimum values in a numpy array with a small number of elements
(Diary 1) How to create, reference, and register data in the SQL database of Microsoft Azure service with python
Various ways to read the last line of a csv file in Python
Feel free to write a test with nose (in the case of + gevent)
How to drop Google Docs in one folder in a .txt file with python
Create a simple reception system with the Python serverless framework Chalice and Twilio
Zip-compress any file with the [shell] command to create a file and delete the original file.
Create a Django project and application in a Python virtual environment and start the server
Get the stock price of a Japanese company with Python and make a graph
How to get a list of files in the same directory with python
An introduction to cross-platform GUI software made with Python / Tkinter! (And many Try and Error)! (In the middle of writing)
Create a GIF file using Pillow in Python
Get the caller of a function in Python
How to create a JSON file in Python
Create a virtual environment with conda in Python
Make a copy of the list in Python
Create a new page in confluence with Python
Output in the form of a python array
Create a Photoshop format file (.psd) with python
Convert the character code of the file with Python3
Create a MIDI file in Python using pretty_midi
A discussion of the strengths and weaknesses of Python
When a file is placed in the shared folder of Raspberry Pi, the process is executed.
Automate background removal for the latest portraits in a directory with Python and API
[Example of Python improvement] I learned the basics of Python on a free site in 2 weeks.
Get the value of a specific key in a list from the dictionary type in the list with Python
How to identify the element with the smallest number of characters in a Python list?
The result of making a map album of Italy honeymoon in Python and sharing it
[Python] Change the text color and background color of a specific keyword in print output
A memo that implements the job of loading a GCS file into BigQuery in Python
[Python] Leave only the elements that start with a specific character string in the array
Python2 / numpy> Replace only a specific column in a file with column data from another file> numpy.c_
Get the file name in a folder using glob