多行文本内容替换工具,
import osimport tkinter as tk
from tkinter import filedialog
import glob
def replace_content():
folder_path = folder_path_var.get()
old_content = old_content_text.get("1.0", "end-1c")
new_content = new_content_text.get("1.0", "end-1c")
if not os.path.isdir(folder_path):
status_label.config(text="请选择有效的文件夹路径", fg="red")
return
file_types = [("DAT files", "*.dat"), ("PPB files", "*.ppb"), ("TXT files", "*.txt")]
files = []
for file_type in file_types:
files.extend(glob.glob(os.path.join(folder_path, file_type)))
if not files:
status_label.config(text="文件夹中没有找到指定类型的文件", fg="red")
return
for file_path in files:
with open(file_path, 'rb') as file:
content = file.read()
content = content.replace(old_content.encode('utf-8'), new_content.encode('utf-8'))
with open(file_path, 'wb') as file:
file.write(content)
status_label.config(text="替换完成", fg="green")
def browse_folder():
folder_path = filedialog.askdirectory()
folder_path_var.set(folder_path)
# 创建主窗口
root = tk.Tk()
root.title("文件内容替换工具")
# 文件夹路径输入框和选择按钮
folder_path_var = tk.StringVar()
folder_path_label = tk.Label(root, text="文件夹路径:")
folder_path_label.grid(row=0, column=0, padx=5, pady=5)
folder_path_entry = tk.Entry(root, textvariable=folder_path_var, width=50)
folder_path_entry.grid(row=0, column=1, padx=5, pady=5)
browse_button = tk.Button(root, text="选择文件夹", command=browse_folder)
browse_button.grid(row=0, column=2, padx=5, pady=5)
# 被替换内容输入框
old_content_label = tk.Label(root, text="被替换内容:")
old_content_label.grid(row=1, column=0, padx=5, pady=5)
old_content_text = tk.Text(root, height=5, width=50)
old_content_text.grid(row=1, column=1, padx=5, pady=5)
# 新内容输入框
new_content_label = tk.Label(root, text="新内容:")
new_content_label.grid(row=2, column=0, padx=5, pady=5)
new_content_text = tk.Text(root, height=5, width=50)
new_content_text.grid(row=2, column=1, padx=5, pady=5)
# 替换按钮
replace_button = tk.Button(root, text="替换", command=replace_content)
replace_button.grid(row=3, column=1, padx=5, pady=5)
# 状态栏
status_label = tk.Label(root, text="", fg="green")
status_label.grid(row=4, column=1, padx=5, pady=5)
root.mainloop()
请问,这个是只支持TXT文件吗?
页:
[1]