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

 更新时间:2024年12月28日 15:46:45   作者:hvinsion  
这篇文章主要为大家详细介绍了Python如何实现按条件批量删除TXT文件中行的工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python中subprocess模块用法实例详解

    Python中subprocess模块用法实例详解

    这篇文章主要介绍了Python中subprocess模块用法,实例分析了subprocess模块的相关使用技巧,需要的朋友可以参考下
    2015-05-05
  • Python装饰器用法与知识点小结

    Python装饰器用法与知识点小结

    这篇文章主要介绍了Python装饰器用法与知识点,总结分析了Python 装饰器的基本概念、原理、用法与操作注意事项,需要的朋友可以参考下
    2020-03-03
  • 对Django中static(静态)文件详解以及{% static %}标签的使用方法

    对Django中static(静态)文件详解以及{% static %}标签的使用方法

    今天小编就为大家分享一篇对Django中static(静态)文件详解以及{% static %}标签的使用方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • pandas中quantile()函数的应用及说明

    pandas中quantile()函数的应用及说明

    本文介绍了pandas中quantile()函数用于计算DataFrame或Series中数值型数据的分位数,通过示例展示了如何计算整个DataFrame、每列和每行的分位数,并可指定百分位数和axis参数进行计算
    2026-05-05
  • Numpy中的shape函数的用法详解

    Numpy中的shape函数的用法详解

    这篇文章主要介绍了Numpy中的shape函数的用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • python实现求最长回文子串长度

    python实现求最长回文子串长度

    最长回文子串问题:给定一个字符串,求它的最长回文子串长度。如果一个字符串正着读和反着读是一样的,那它就是回文串。今天我们就来探讨下这个问题
    2018-01-01
  • 520必备!这些Python表白代码祝你脱单成功

    520必备!这些Python表白代码祝你脱单成功

    不会还有程序猿没有女朋友吧?没关系,今天特地为大家整理了这些Python花式表白代码,你就放心大胆的去吧,需要的朋友可以参考下
    2021-05-05
  • python中的tcp示例详解

    python中的tcp示例详解

    这篇文章主要给大家介绍了关于python中tcp协议的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-12-12
  • python创建子类的方法分析

    python创建子类的方法分析

    这篇文章主要介绍了python创建子类的方法,结合实例形式分析了Python子类的具体定义与使用方法,需要的朋友可以参考下
    2019-11-11
  • Python脚本实现批量导出网站指定文章

    Python脚本实现批量导出网站指定文章

    这篇文章主要为大家详细介绍了如何利用Python脚本实现批量导出网站指定文章,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2026-02-02

最新评论