吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2313|回复: 20
收起左侧

[Windows] 合并txt小说输出为一个txt文件;并且把文件名分割作为标题;保持目录

[复制链接]
Hf6824329 发表于 2025-7-30 11:11
Snipaste_2025-07-30_11-05-54.png
度娘:链接: https://pan.baidu.com/s/1foD-1-D8uJS6gYxS6Jsmng?pwd=hzhz 提取码: hzhz



import os
import tkinter as tk
from tkinter import filedialog, messagebox
def merge_txt_files(input_dir, output_file):
    """合并指定目录下的所有txt文件到一个输出文件"""
    # 确保输出目录存在
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
   
    # 获取所有txt文件并按名称排序
    txt_files = sorted([f for f in os.listdir(input_dir) if f.endswith('.txt')])
   
    if not txt_files:
        messagebox.showwarning("警告", "所选目录下没有找到txt文件!")
        return
   
    # 合并文件内容
    with open(output_file, 'w', encoding='utf-8') as outfile:
        for txt_file in txt_files:
            file_path = os.path.join(input_dir, txt_file)
            try:
                # 尝试多种编码方式读取文件
                encodings = ['utf-8', 'gbk', 'gb2312', 'ansi']
                content = None
               
                for encoding in encodings:
                    try:
                        with open(file_path, 'r', encoding=encoding) as infile:
                            content = infile.read()
                        break
                    except UnicodeDecodeError:
                        continue
               
                if content is None:
                    raise UnicodeDecodeError(f"无法使用已知编码方式读取文件 {txt_file}")
               
                # 写入文件名作为标题,使用等号装饰
                outfile.write('=' * 20 + '\n')
                outfile.write(f"《{os.path.splitext(txt_file)[0]}\n")
                outfile.write('=' * 20 + '\n\n')
                outfile.write(content)
                outfile.write('\n\n')
            except Exception as e:
                messagebox.showerror("错误", f"处理文件 {txt_file} 时出错: {str(e)}")
class MergeTxtGUI:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("TXT文件合并工具")
        self.window.geometry("600x350")
        
        # 添加说明标签
        self.info_label = tk.Label(self.window,
                                 text="本工具用于合并指定目录下的所有TXT文件,并在合并时添加文件名作为标题",
                                 wraplength=550)
        self.info_label.pack(pady=10)
        
        # 创建输入目录选择部分
        self.input_frame = tk.Frame(self.window)
        self.input_frame.pack(pady=20)
        
        self.input_label = tk.Label(self.input_frame, text="输入目录:")
        self.input_label.pack(side=tk.LEFT)
        
        self.input_entry = tk.Entry(self.input_frame, width=50)
        self.input_entry.pack(side=tk.LEFT, padx=5)
        
        self.input_button = tk.Button(self.input_frame, text="浏览", command=self.select_input_dir)
        self.input_button.pack(side=tk.LEFT)
        
        # 创建输出文件选择部分
        self.output_frame = tk.Frame(self.window)
        self.output_frame.pack(pady=20)
        
        self.output_label = tk.Label(self.output_frame, text="输出文件:")
        self.output_label.pack(side=tk.LEFT)
        
        self.output_entry = tk.Entry(self.output_frame, width=50)
        self.output_entry.pack(side=tk.LEFT, padx=5)
        
        self.output_button = tk.Button(self.output_frame, text="浏览", command=self.select_output_file)
        self.output_button.pack(side=tk.LEFT)
        
        # 创建合并按钮
        self.merge_button = tk.Button(self.window, text="开始合并",
                                    command=self.start_merge,
                                    width=20,
                                    height=2)
        self.merge_button.pack(pady=20)
        
    def select_input_dir(self):
        directory = filedialog.askdirectory(title="选择包含TXT文件的目录")
        if directory:
            self.input_entry.delete(0, tk.END)
            self.input_entry.insert(0, directory)
   
    def select_output_file(self):
        file_path = filedialog.asksaveasfilename(
            title="选择保存位置",
            defaultextension=".txt",
            filetypes=[("Text files", "*.txt")]
        )
        if file_path:
            self.output_entry.delete(0, tk.END)
            self.output_entry.insert(0, file_path)
   
    def start_merge(self):
        input_dir = self.input_entry.get()
        output_file = self.output_entry.get()
        
        if not input_dir or not output_file:
            messagebox.showerror("错误", "请选择输入目录和输出文件路径!")
            return
        
        try:
            merge_txt_files(input_dir, output_file)
            messagebox.showinfo("成功", f"合并完成!\n输出文件: {output_file}")
        except Exception as e:
            messagebox.showerror("错误", f"合并过程出错: {str(e)}")
if __name__ == "__main__":
    app = MergeTxtGUI()
    app.window.mainloop()

免费评分

参与人数 2吾爱币 +2 热心值 +2 收起 理由
云可弦 + 1 + 1 谢谢@Thanks!
lilgegg + 1 + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

cnvip666 发表于 2025-8-3 10:38
整理小说神器,支持一下。
jxwuguohua1977 发表于 2025-9-14 16:56
感谢楼主分享!楼主,最大能支持合并多大的 txt 文件?一本 txt 电子书就是10M甚至有20几M大小,若是多几本合并,程序会不会崩溃?
 楼主| Hf6824329 发表于 2025-7-30 17:32
这个工具我感觉好用额咋木有人用;像盗墓笔记;直接7-8本合成一本;合并的文件名会内置成标题
emberzhang 发表于 2025-8-1 22:18
能查出文件里的重复部分吗
dabaimuxing2012 发表于 2025-8-2 12:31
上学的时候同学都是把分本的TXT粘贴到一个里面,从头选到尾可费劲了
chenci199 发表于 2025-8-2 15:01
大佬功德无量,感谢!
88059516 发表于 2025-8-2 15:11
一些散的短文可以合到一个文本!
thj7332 发表于 2025-8-2 15:40
不看小说是不是没什么用了
taoyie 发表于 2025-8-2 16:33
感谢,偶尔hi是会用到这个软件,
头像被屏蔽
宁愿二不愿装 发表于 2025-8-3 10:52
提示: 作者被禁止或删除 内容自动屏蔽
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-12-17 10:33

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表