(office class-05) batch modify the file name of docx

Office demand

Recently, I have been making batch templates of routine materials (weekly plan, information window, theme knowledge and parenting knowledge). After I batch generated the 20 week content of the information window and subject knowledge, I spent two hours to fine tune the content of the information window inside (this is a set of information window three years ago, and some contents are not suitable for the current post epidemic environment).

After the correction, I suddenly found that the weekly word file name was wrong - I wrote "information window parenting knowledge of week 3 (next semester of class 8)", and the correct way is "information window theme knowledge of week 3 (next semester of class 8)"

Solution ideas

Since a large number of words have been manually modified in the 20 point word (not the original content called from the excel template), I have two choices:

First: open each generated information window word, and paste the updated content into the corresponding position of Excel again by week. Then modify the batch file name in the code and run it for the last time. You can get the file name of "theme knowledge of week 3 information window (next semester of class 8). (paste the correct content into excel and adjust it repeatedly.)

Second, directly through Python code, change the word that has generated 20 information windows into new file names in batch.

Treatment method:

In order to change quickly, I still searched for "code for changing file names in batch in word", Risun_Lee's multi-functional code quickly replaced my 20 "week x information window parenting knowledge (next semester of class 8). docx" with 20 "week x information window theme knowledge (next semester of class 8) in one second, which is very practical.

Code: plan word to modify the file name of docx in batch

'''
Author: Risun_Lee
 Original address: https://www.cnblogs.com/risunlee/p/13630526.html
'''


# system module
import os
import re
import tkinter
import tkinter.messagebox
import tkinter.filedialog
import tkinter.ttk
import sys
import logging

logger = logging.getLogger(__name__)

def create_logger(filename="log.txt", level=logging.INFO, console_swtich = True):
    # Get the logger instance. If the parameter is empty, the root logger is returned
    # logger = logging.getLogger(__name__)

    # Create log output format
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d][%(funcName)s] - %(levelname)s - %(message)s")

    # Specifies the file path for the output
    file_handler = logging.FileHandler(filename)
    # Format file processor
    file_handler.setFormatter(formatter)

    # Log processor added for logger
    logger.addHandler(file_handler)

    # console log 
    if console_swtich:
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.formatter = formatter
        logger.addHandler(console_handler)

    # Specifies the minimum output level of the log. The default is warn level
    logger.setLevel(level)

    return logger

class modify_string():
    #Interface layout method
    def __init__(self):
        #Create the interface and save it to the member properties
        self.root = tkinter.Tk()
        self.root.minsize(400, 170)
        self.root.resizable(0, 0)
        self.root.title("Batch modify string")

        #Folder path
        self.path = tkinter.StringVar()
        self.path.set("")

        #option
        self.folder_name = tkinter.IntVar()
        self.file_name = tkinter.IntVar()
        self.file_content = tkinter.IntVar()

        #character string
        self.string_old = tkinter.StringVar()
        self.string_new = tkinter.StringVar()

        #speed of progress
        self.progress = tkinter.StringVar()
        self.progress.set("Start modification")

        #Interface layout
        self.menus()
        self.layout()
        self.root.mainloop()

    def menus(self):
        #add menu

        #Create general menu
        allmenu = tkinter.Menu(self.root)

        # Add submenu 1
        debugmenu = tkinter.Menu(allmenu, tearoff=0)
        debugmenu.add_command(label="journal",
                              command=self.log)

        allmenu.add_cascade(label="debugging",
                            menu=debugmenu)

        # Add submenu 2
        helpmenu = tkinter.Menu(allmenu, tearoff=0)

        # Add Tab 
        helpmenu.add_command(label='rule',
                             command=self.rule)
        helpmenu.add_command(label='Version Description',
                             command=self.release_note)
        helpmenu.add_command(label='about',
                             command=self.about)

        allmenu.add_cascade(label='help',
                            menu=helpmenu)

        tkinter.ttk.Separator(self.root, orient="horizontal").pack(fill="x", padx=0)


        self.root.config(menu=allmenu)

    def layout(self):
        #layout
        #Folder path
        path_description = tkinter.Label(self.root,
                                         font=("Song style", 10),
                                         fg="blue",
                                         anchor="w",
                                         text="Folder path")
        path_description.place(x=5, y=10, width=70, height=20)

        path_show = tkinter.Label(self.root,
                                  bd=3,
                                  bg='white',
                                  font=("Song style", 10),
                                  anchor="e",
                                  textvariable=self.path)
        path_show.place(x=80, y=10, width=250, height=20)

        button_path = tkinter.Button(self.root,
                                     text='choice',
                                     command=self.select_path)
        button_path.place(x=335, y=10, width=60, height=20)

        # option
        option = tkinter.Label(self.root,
                               font=("Song style", 10),
                               fg="blue",
                               anchor="w",
                               text="Modify options")
        option.place(x=5, y=40, width=70, height=20)

        folder_select =tkinter.Checkbutton(self.root,
                                           text="Folder name",
                                           anchor="w",
                                           variable=self.folder_name)
        folder_select.place(x=80, y=40, width=100, height=20)

        folder_select = tkinter.Checkbutton(self.root,
                                            text="File name",
                                            anchor="w",
                                            variable=self.file_name)
        folder_select.place(x=185, y=40, width=100, height=20)

        folder_select = tkinter.Checkbutton(self.root,
                                            text="Document content",
                                            anchor="w",
                                            variable=self.file_content)
        folder_select.place(x=290, y=40, width=100, height=20)

        #character string
        tkinter.Label(self.root,
                      font=("Song style", 10),
                      fg="blue",
                      anchor="w",
                      text="Original string").place(x=5, y=70, width=70, height=20)
        source_text = tkinter.Entry(self.root,
                                    textvariable=self.string_old)
        source_text.place(x=80, y=70, width=310, height=20)

        tkinter.Label(self.root,
                      font=("Song style", 10),
                      fg="blue",
                      anchor="w",
                      text="New string").place(x=5, y=100, width=70, height=20)
        source_text = tkinter.Entry(self.root,
                                    textvariable=self.string_new)
        source_text.place(x=80, y=100, width=310, height=20)

        # Start modification
        button_start = tkinter.Button(self.root,
                                      font=("Song style", 12),
                                      text="Start modification",
                                      command=self.start)
        button_start.place(x=165, y=130, width=70, height=30)

    def matchcase(self, word):
        return word
        # def rmodify(m):
        #     # re.sub will pass in the matched object by calling the modify method in a loop
        #
        #     # Get matching text
        #     text = m.group()
        #
        #     if text.isupper():
        #         # If the text is all uppercase, the all uppercase mode of word is returned
        #         return word.upper()
        #     elif text.islower():
        #         # If the text is all lowercase, the all lowercase mode of word is returned
        #         return word.lower()
        #     elif len(text) > 0 and text[0].isupper():
        #         # If the text is capitalized, the initial capitalization mode of word is returned
        #         return word.capitalize()
        #     else:
        #         # In other cases, directly return to word
        #         return word
        #
        # return modify

    def modify(self, path):
        # Modify the current folder name
        if self.folder_name.get() == 1:
            folder = os.path.basename(path)
            folder = re.sub(self.string_old.get(),
                            self.matchcase(self.string_new.get()),
                            # flags=re.IGNORECASE,
                            folder)
            os.rename(path, os.path.join(os.path.dirname(path), folder))
            path = os.path.join(os.path.dirname(path), folder)

        filenames = os.listdir(path)
        logger.info(f"file list {filenames}")

        for filename in filenames:
            domain = os.path.abspath(path)
            file_path = os.path.join(domain, filename)

            # Recursively modify sub file name, file name and file content
            if os.path.isdir(file_path):
                if self.folder_name.get() == 1:
                    filename = re.sub(self.string_old.get(),
                                      self.matchcase(self.string_new.get()),
                                      # flags=re.IGNORECASE,
                                      filename)
                    os.rename(file_path, os.path.join(domain, filename))
                    file_path = os.path.join(domain, filename)

                logger.debug(f"enter folder {file_path}")
                self.modify(file_path)
                logger.debug(f"exit folder {file_path}\n")
                continue

            # Modify file name
            if self.file_name.get() == 1:
                filename = re.sub(self.string_old.get(),
                                 self.matchcase(self.string_new.get()),
                                  # flags=re.IGNORECASE,
                                 filename)
                os.rename(file_path, os.path.join(domain, filename))
                file_path = os.path.join(domain, filename)

            # Modify file content
            if self.file_content.get() == 1:
                format = file_path.split(".")[-1]
                if format != "c" and format != "h" and format != "txt":
                    logger.info(f"can not process {file_path}")
                    continue;

                fread = open(file_path, 'r')
                fwrite = open("%s.backup" % file_path, 'w')

                while True:
                    line = fread.readline()
                    if len(line) > 0:
                        line = re.sub(self.string_old.get(),
                                      self.matchcase(self.string_new.get()),
                                      # flags=re.IGNORECASE,
                                      line)
                        fwrite.write(line)
                    else:
                        break
                fread.close()
                fwrite.close()
                os.remove(file_path)
                os.rename("%s.backup" % file_path, file_path)

    def start(self):
        if self.path.get() == "":
            tkinter.messagebox.showinfo('error', "Please select a folder path!")
        else:
            logger.info(f'''route:"{self.path.get()}"''')
            logger.info("Modify options:")
            option_count = 0
            if self.folder_name.get() == 1:
                option_count = option_count + 1
                logger.info(f"  {option_count}. Folder name")
            if self.file_name.get() == 1:
                option_count = option_count + 1
                logger.info(f"  {option_count}. File name")
            if self.file_content.get() == 1:
                option_count = option_count + 1
                logger.info(f"  {option_count}. Document content")
            logger.info(f"Original string:{self.string_old.get()}")
            logger.info(f"New string:{self.string_new.get()}")
            self.modify(self.path.get())
            tkinter.messagebox.showinfo('result', "Modification completed")

    def log(self):
        os.startfile("log.txt")
        # domain = os.path.abspath(os.getcwd())
        # log_path = os.path.join(domain, "log")
        #
        # log = open(log_path, 'r')
        # log.close()

    def rule(self):
        tkinter.messagebox.showinfo('Batch modify string rule',
                                    "1.Modify the name of the current folder and subfolders;\n"
                                    "2.Modify the names of all files in the current folder and subfolders;\n"
                                    "3.Modify the contents of all files in the current folder and subfolders;\n")

    def about(self):
        tkinter.messagebox.showinfo('Batch modify string',
                                    "Author: Risun_Lee\n"
                                    "edition: V1.0\n"
                                    "Release date: 2020 September 8\n")

    def release_note(self):
        tkinter.messagebox.showinfo('Version Description',
                                    "V1.0:\n"
                                    "1.Support the modification of folder name and file name;\n"
                                    "2.support txt,c,h Modification of document content;\n")

    def select_path(self):
        path = tkinter.Tk()
        path.withdraw()
        fpath = os.path.normpath(tkinter.filedialog.askdirectory())
        if fpath != ".":
            self.path.set(str(fpath))

def main():
    create_logger(level=logging.DEBUG)
    modify_string()

if __name__ == '__main__':
    main()

This code is made into EXE, which can be selected in many ways. Here I choose to modify the file name of 20 word s and change "parenting knowledge" into "subject knowledge" in batch.

This code can also be used to modify the content of word files, replace the text in 20 copies of word, bold, etc.

 



:
 

This code can also Change docx to xlsx or JPG format.

Keywords: Python

Added by Boris Senker on Sat, 05 Mar 2022 08:49:26 +0200