Merge multiple text files

A blog for merging multiple text files using the wxPython module. Here is an example blog:
C:\pythoncode\blog\txtmerge.py

insert image description here

In Python programming, we often need to deal with text files. Sometimes, we may need to combine multiple text files into one file for further processing or analysis. In this article, we will describe how to use the wxPython module to write a simple program that allows the user to select multiple text files and merge them into one file in the order in which they were selected.

Preparation

First, we need to install the wxPython module. You can use the following command to install:

pip install wxPython

After the installation is complete, we can start writing programs.

Programming

We will use the wxPython module to create a simple GUI program. Users can select the text files to be merged through this program, and merge them into one file according to the order of selection.

Here is the code for the program:

import wx
import datetime
import os

class MergeApp(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="文档合并工具", size=(400, 300))
        
        self.panel = wx.Panel(self)
        
        self.file_list = wx.ListBox(self.panel, style=wx.LB_MULTIPLE)
        self.merge_button = wx.Button(self.panel, label="合并文档")
        self.merge_button.Bind(wx.EVT_BUTTON, self.on_merge)
        
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.file_list, 1, wx.EXPAND | wx.ALL, 10)
        self.sizer.Add(self.merge_button, 0, wx.ALIGN_CENTER | wx.ALL, 10)
        
        self.panel.SetSizer(self.sizer)
        
    def on_merge(self, event):
        selected_files = self.file_list.GetSelections()
        if len(selected_files) < 2:
            wx.MessageBox("请选择至少两个文档进行合并!", "错误", wx.OK | wx.ICON_ERROR)
            return
        
        merged_content = ""
        
        for index in selected_files:
            file_path = self.file_list.GetString(index)
            with open(file_path, "r", encoding="utf-8") as file:
                merged_content += file.read()
        
        merge_datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        merge_filename = f"merge_{
      
      merge_datetime}.txt"
        
        with open(merge_filename, "w", encoding="utf-8") as merged_file:
            merged_file.write(merged_content)
        
        wx.MessageBox(f"文档合并完成,合并文档保存为 {
      
      merge_filename}!", "完成", wx.OK | wx.ICON_INFORMATION)
        
        self.Close()
        
if __name__ == "__main__":
    app = wx.App()
    frame = MergeApp()
    
    wildcard = "Text files (*.txt)|*.txt"
    dialog = wx.FileDialog(None, message="请选择要合并的文档", wildcard=wildcard, style=wx.FD_OPEN | wx.FD_MULTIPLE)
    
    if dialog.ShowModal() == wx.ID_OK:
        file_paths = dialog.GetPaths()
        frame.file_list.AppendItems(file_paths)
    
    dialog.Destroy()
    
    frame.Show()
    app.MainLoop()

run the program

Save the above code as merge_app.pya file. Then, start the program by running the following command at the command line:

python merge_app.py

The program window will be displayed and you can click the "Browse" button to select the text files to merge. The selected files will be displayed in the list box. After selecting at least two files, click the "Merge Documents" button, the program will merge the contents of the files into a new text file according to the order of selection, and display the information of the merge completion in the pop-up message box.

all codes

import wx
import datetime
import os

class MergeApp(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="文档合并工具", size=(400, 300))
        
        self.panel = wx.Panel(self)
        
        self.file_list = wx.ListBox(self.panel, style=wx.LB_MULTIPLE)
        self.merge_button = wx.Button(self.panel, label="合并文档")
        self.merge_button.Bind(wx.EVT_BUTTON, self.on_merge)
        
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.file_list, 1, wx.EXPAND | wx.ALL, 10)
        self.sizer.Add(self.merge_button, 0, wx.ALIGN_CENTER | wx.ALL, 10)
        
        self.panel.SetSizer(self.sizer)
        
    def on_merge(self, event):
        selected_files = self.file_list.GetSelections()
        if len(selected_files) < 2:
            wx.MessageBox("请选择至少两个文档进行合并!", "错误", wx.OK | wx.ICON_ERROR)
            return
        
        merged_content = ""
        
        for index in selected_files:
            file_path = self.file_list.GetString(index)
            with open(file_path, "r", encoding="utf-8") as file:
                merged_content += file.read()
        
        merge_datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        merge_filename = f"merge_{
      
      merge_datetime}.txt"
        
        with open(merge_filename, "w", encoding="utf-8") as merged_file:
            merged_file.write(merged_content)
        
        wx.MessageBox(f"文档合并完成,合并文档保存为 {
      
      merge_filename}!", "完成", wx.OK | wx.ICON_INFORMATION)
        
        self.Close()
        
if __name__ == "__main__":
    app = wx.App()
    frame = MergeApp()
    
    wildcard = "Text files (*.txt)|*.txt"
    dialog = wx.FileDialog(None, message="请选择要合并的文档", wildcard=wildcard, style=wx.FD_OPEN | wx.FD_MULTIPLE)
    
    if dialog.ShowModal() == wx.ID_OK:
        file_paths = dialog.GetPaths()
        frame.file_list.AppendItems(file_paths)
    
    dialog.Destroy()
    
    frame.Show()
    app.MainLoop()

Summarize

By using the wxPython module, we wrote a simple program that conveniently merges multiple text files. The program provides a user-friendly interface that enables users to easily select files and perform merge operations. You can modify and extend the code according to your needs to meet more specific requirements.

Hope this blog was helpful to you! If you have any other questions, please feel free to ask.

Guess you like

Origin blog.csdn.net/winniezhang/article/details/132378441