本帖最后由 wesley1224 于 2024-2-4 18:05 编辑
朋友叫的需求,目前在自学python中,自写的TXT文本提取小工具,送给用得上的朋友。语言:python.
功能:把路径下的所有文件夹内的 txt 提取到一个output.txt内,按文件名+内容显示。
解压密码:52pojie
2024-02-04 同时开源,源码很简单。
小修正:为了确保输出的内容严格按照.txt文件的顺序排列,不使用线程池进行并发处理了,而是改为顺序处理每个文件。
[Python] 纯文本查看 复制代码 import os
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
def search_txt_files(dir_path):
return [os.path.join(root, file_name) for root, dirs, files in os.walk(dir_path)
for file_name in files if file_name.endswith(".txt")]
def process_txt(txt_file):
with open(txt_file, 'r', encoding="utf-8") as txt:
return f"{os.path.basename(txt_file)} {txt.read()}"
def write_txt(dir_path, output_file='output.txt'):
txt_files = search_txt_files(dir_path)
processed_contents = []
for txt_file in txt_files:
try:
data = process_txt(txt_file)
processed_contents.append(data)
except Exception as exc:
print(f"Failed to process {txt_file}: {exc}")
with open(os.path.join(dir_path, output_file), 'w', encoding="utf-8") as f:
for content in processed_contents:
f.write(f"{content}\n")
def show_message_box(default_path):
def validate_and_write():
user_path = entry.get()
if os.path.isdir(user_path):
write_txt(user_path)
else:
messagebox.showerror("错误", "请提供有效的目录路径。")
root = tk.Tk()
root.title("TXT文本提取合成工具 by wesley_net")
root.geometry('350x200')
label_title = tk.Label(root, text="请输入或粘贴路径", font=("Arial", 20))
label_title.pack(pady=10)
entry = tk.Entry(root, width=45, justify=tk.LEFT)
entry.insert(0, default_path)
entry.pack(pady=10)
button_ok = tk.Button(root, text="确定", command=validate_and_write)
button_close = tk.Button(root, text="关闭", command=root.quit)
button_ok.place(x=120, y=150, anchor='center', width=70)
button_close.place(x=190, y=150, anchor='w', width=70)
root.mainloop()
current_directory = os.getcwd()
show_message_box(current_directory)
https://wwt.lanzoul.com/b00s259id
密码:5re7 |