当前位置: 代码网 > it编程>前端脚本>Python > Python按条件批量删除TXT文件行工具

Python按条件批量删除TXT文件行工具

2024年12月29日 Python 我要评论
1.简介一个由python编写的可根据txt文件按条件批量删除行工具,资源及文件已打包成exe文件功能:批量删除行含关键字或词的行(多个关键字/词中间用空格隔开)批量删除空行批量字符小于多少(可设定)

1.简介

一个由python编写的可根据txt文件按条件批量删除行工具,资源及文件已打包成exe文件

功能:

  • 批量删除行含关键字或词的行(多个关键字/词中间用空格隔开)
  • 批量删除空行
  • 批量字符小于多少(可设定)删除行
  • 批量删除匹配正则的行

使用方法:

  • 点击打开文件批量选择txt文件(可以直接拖拽)。
  • 需要的功能前打勾,并配置。
  • 点击【执行】即可进行转换。
  • 最后会生成原文件名+_new.txt的文件。

2.运行效果

3.相关源码

import os
import re
import time
from tkinter import ttk, filedialog, messagebox, insert, tk, button, text, scrollbar, \
    horizontal, vertical, intvar, checkbutton, label, stringvar, entry  # 有combobox、labelframe 组件时需要本语句
import windnd
 
ui_pos = {
    "title": "txt文件处理助手",
    "geometry": "450x300",  # 长乘宽
 
}
 
filepaths = ()
 
 
def clearall():
    ctrl_filelistbox.delete(1.0, "end")  # 清空文件路径
    str_keyword.set("")
    str_keynum.set("")
 
 
def gettxtfiles():
    global filepaths
    files = filedialog.askopenfilenames(filetypes=[('text files', '.txt')])
    if files:
        filepaths = files
        for f_name in files:
            ctrl_filelistbox.insert('end', f_name)
            ctrl_filelistbox.insert(insert, '\n')
    else:
        messagebox.showinfo(title='提示', message='没有选择任何文件!')
 
 
def keywordscan(keys, s):
    key_words = keys.split(" ")
    t_f = false
    for key_word in key_words:
        if key_word in s:
            t_f = true
    return t_f
 
 
def ctrl_startbtn_clicked():
    has_key_words = int_checkbox1.get()
    key_words = str_keyword.get()
 
    has_empty_line = int_checkbox2.get()
 
    has_n = int_checkbox3.get()
    n = str_keynum.get()
 
    has_zz = int_checkbox4.get()
    zz = str_zz.get()
    try:
        for file in filepaths:  # 循环遍历文件
            s_file = open(os.path.splitext(file)[0] + "_new" + os.path.splitext(file)[1], 'w+')  # 文件保存位置
            f_lines = open(file, encoding='utf8').readlines()  # 打开文件,读入每一行
            for s in f_lines:  # s: 每一行的内容
                # 操作1
                if has_key_words:
                    if keywordscan(key_words, s):
                        continue
                # 操作2
                if has_empty_line:
                    if len(s.strip()) == 0:
                        continue
                # 操作3:
                if has_n:
                    if len(s.strip()) < int(n):
                        continue
                if has_zz:
                    if re.match(zz, s.strip()):
                        continue
                s_file.write(s)
            s_file.close()  # 关闭文件
    except exception as e:
        with open("log", "a+") as f:
            f.write(time.strftime("%y-%m-%d, %h:%m:%s", time.localtime()) + "\n")
            f.write(repr(e) + "\n")
 
 
def draggedfiles(files):
    msg = '\n'.join((item.decode('gbk') for item in files))
    for f_name in files:
        ctrl_filelistbox.insert('end', f_name)
        ctrl_filelistbox.insert(insert, '\n')
    print(msg)
 
 
root = tk()  # 设定窗体变量
root.geometry(ui_pos["geometry"])  # 格式('宽x高+x+y')其中x、y为位置
root.title(ui_pos["title"])
windnd.hook_dropfiles(root, func=draggedfiles)
 
ctrl_frame1 = ttk.labelframe(root, text='选项')
ctrl_frame1.place(x=14, y=72, width=388, height=140)
 
ctrl_startbtn = button(root, text='执行', font=('宋体', '9'),
                       command=ctrl_startbtn_clicked)  # 可在括号内加上调用函数部分 ,command=ctrl_startbtn_clicked
ctrl_startbtn.place(x=22, y=250, width=72, height=29)
 
ctrl_quitbtn = button(root, text='清除', font=('宋体', '9'), command=clearall)  # 可在括号内加上调用函数部分 ,command=ctrl_quitbtn_clicked
ctrl_quitbtn.place(x=108, y=250, width=72, height=29)
 
ctrl_filelistbox = text(root, font=('宋体', '9'))
ctrl_filelistbox.place(x=14, y=7, width=260, height=38)
ctrl_scrollbar1 = scrollbar(root, command=ctrl_filelistbox.xview, orient=horizontal)
ctrl_scrollbar1.place(x=14, y=46, width=261, height=16)
ctrl_scrollbar2 = scrollbar(root, command=ctrl_filelistbox.yview, orient=vertical)
ctrl_scrollbar2.place(x=275, y=7, width=16, height=39)
ctrl_filelistbox.config(xscrollcommand=ctrl_scrollbar1.set, yscrollcommand=ctrl_scrollbar2.set, wrap='none')
 
int_checkbox1 = intvar()  # 绑定变量
ctrl_checkbox1 = checkbutton(ctrl_frame1, text='删除行含关键字或词的行', variable=int_checkbox1, font=('宋体', '9'))
ctrl_checkbox1.place(x=14, y=14, height=22)  # 考虑到对齐问题,不列入宽度,需要时手动加入 width=130
ctrl_checkbox1.deselect()  # 默认为未选中状态
 
ctrl_label1 = label(ctrl_frame1, text="关键字:")
ctrl_label1.place(x=180, y=14, width=55, height=22)
 
str_keyword = stringvar()  # 绑定变量
ctrl_keyword = entry(ctrl_frame1, textvariable=str_keyword, font=('宋体', '9'))
ctrl_keyword.place(x=230, y=14, width=150, height=22)
 
int_checkbox2 = intvar()  # 绑定变量
ctrl_checkbox2 = checkbutton(ctrl_frame1, text='删除空行', variable=int_checkbox2, font=('宋体', '9'))
ctrl_checkbox2.place(x=14, y=36, height=22)  # 考虑到对齐问题,不列入宽度,需要时手动加入 width=130
ctrl_checkbox2.deselect()  # 默认为未选中状态
 
int_checkbox3 = intvar()  # 绑定变量
ctrl_checkbox3 = checkbutton(ctrl_frame1, text='删除字符小于n的行', variable=int_checkbox3, font=('宋体', '9'))
ctrl_checkbox3.place(x=14, y=58, height=22)  # 考虑到对齐问题,不列入宽度,需要时手动加入 width=130
ctrl_checkbox3.deselect()  # 默认为未选中状态
# n标签
ctrl_label = label(ctrl_frame1, text="n =")
ctrl_label.place(x=180, y=58, width=55, height=22)
# n
str_keynum = stringvar()  # 绑定变量
ctrl_keynum = entry(ctrl_frame1, textvariable=str_keynum, font=('宋体', '9'))
ctrl_keynum.place(x=230, y=58, width=30, height=22)
 
int_checkbox4 = intvar()  # 绑定变量
ctrl_checkbox4 = checkbutton(ctrl_frame1, text='删除符合正则的行', variable=int_checkbox4, font=('宋体', '9'))
ctrl_checkbox4.place(x=14, y=80, height=22)  # 考虑到对齐问题,不列入宽度,需要时手动加入 width=130
ctrl_checkbox4.deselect()  # 默认为未选中状态
 
# n标签
ctrl_label2 = label(ctrl_frame1, text="正则:")
ctrl_label2.place(x=180, y=80, width=55, height=22)
# n
str_zz = stringvar()  # 绑定变量
ctrl_zz = entry(ctrl_frame1, textvariable=str_zz, font=('宋体', '9'))
ctrl_zz.place(x=230, y=80, width=150, height=22)
 
ctrl_openfilebtn = button(root, text='选择文件',
                          font=('宋体', '9'),
                          command=gettxtfiles)  # 可在括号内加上调用函数部分 ,command=ctrl_openfilebtn_clicked
ctrl_openfilebtn.place(x=305, y=18, width=72, height=29)
 
root.mainloop()

到此这篇关于python按条件批量删除txt文件行工具的文章就介绍到这了,更多相关python批量删除txt内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com