python + tkinter 批量插入文件内容小工具

本文介绍了一个使用Python和tkinter库的小工具,该工具能够批量地将特定字符串插入到指定文件夹及其子文件夹中的所有指定后缀名文件内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


先贴个图:
在这里插入图片描述
这里没有把插入的内容,关键字等信息开放出来,当然看完文章的人做这些我相信是很简单的。

一 环境准备

最近遇到一个需要把固定许可字符串批量插入到指定文件夹中(包括子文件)的指定后缀名文件的场景,考虑再三,在windows下还是用python实现会比较简单。

1.1 pycharm下载与安装

python的工具很多,pycharm是我比较中意的一个软件。下载简单,官网免费下载即可,贴上链接:

链接: pycharm官网下载地址

1.2 pycharm 中文设置

下载完pycharm后新建一个项目,对于python来说不需要繁多的手动操作,一切交给系统,秉持着简单至上的原则,本文只用一个py文件解决问题,当然这也反应了用简单的ide也能完成任务。
这里简单说明下pycharm下载中文包的步骤。
打开 界面左上角file -> settings->Plugins,然后在搜索框中输入Chinese 后,在筛选出来的工具中选择Chinese(simplified)Language,安装后重启就是中文简体版了,当然习惯英文版本的不用下载,毕竟英文版本稳定些。

二 界面部分

tkinter 是一个简单的库,也是python自带的库,最新版本大小约为129k,不需要额外下载,直接import需要的内容即可。界面部分代码如下

import tkinter as tk


def TKShow():
    window = tk.Tk()
    window.title("插入导航内容")
    window.geometry("500x150+650+300")
    window.resizable(False, False)

    # 设置回调函数
    def callback():
        #打开文件对话框
        print("暂无打开操作")

    def callback2():
        #获取所有文件路径
		print("暂无获取操作")

    # 使用按钮控件调用函数
    button = tk.Button(window, text="选择文件夹", command=callback)
    button.grid(column=0, row=0,padx=10,pady=10)

    entry = tk.Entry(window,width=65)
    entry.grid(column=0, row=1, padx=5, pady=10)

    button2 = tk.Button(window, text="批量写入", command=callback2)
    button2.grid(column=0, row=3, padx=10, pady=10)

    window.mainloop()
    
if __name__ == '__main__':
    TKShow()

上面代码可以直接运行,界面部分已经创建完毕,其中简单来说分为了两个部分,一个是界面布局,另一个是绑定回调,当然回调内容暂时没写上去,放在下一部分介绍。
程序入口从main开始,进入TKShow()函数中,创建好布局,我这里用的是grid网格布局,col和row和行和列,这个用过其他网格布局的界面工具应该会很熟悉,padx和pady是控件的位置。button是按钮,entry是输入框。command绑定好回调函数,一个基本界面框架就搭建起来了。

三 文件处理部分

3.1 选择文件夹按钮

界面就三个控件,选择文件夹按钮,文件夹路径输入框,批量写入按钮
选择文件夹按钮被命名为button,绑定了callback()函数,也就是说点击此按钮的时候会进入callback函数,此部分完善函数的内容。

  # 设置回调函数
    def callback():
        #打开文件对话框
        filePath = outputFile()
        #显示在entry上
        entry.delete(0,'end')
        entry.insert(0,filePath)

以上代码的功能就是接受打开文件夹对话框返回的路径,并将此路径显示到界面的输入框中。
现在完成下outputFile函数,这里我们用到了askdirectory()函数,此函数是tkinter 的库函数,会创建文件选择对话框并返回选择的路径。
所以这里也要加一个import,最好是加在项目最上面

from tkinter.filedialog import *

def outputFile():
    outputFilePath = askdirectory()  # 选择目录,返回目录名
    #print(outputFilePath)
    return outputFilePath

批量写入按钮

代码很简单,只是插入的内容有点多,更改keyword的值来确认插入到哪个地方
下面进行了两个关键字的查询,插入了两次字符串
【注:字符串使用r和’‘’ ‘’’ 最好,不然会出现一些格式转换符的问题】

    def callback2():
        #获取所有文件路径
        filePath = entry.get()
        fileList = GetAllFile(filePath)
        AddTextToFile(fileList)
        Message("写入完毕!")

def GetAllFile(outputFilePath):
    p = Path(outputFilePath)  # 初始化构造Path对象
    FileList = list(p.glob("**/*.aspx"))  # 得到所有的markdown文件

def AddTextToFile(FileList):
    for file in FileList:
        InsertHead(file)
        InsertBody(file)

def InsertHead(filePath):
    str = r'''<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-5T3Q7M9');</script>
<!-- End Google Tag Manager -->'''

    file = open(filePath, 'r', encoding='utf-8')
    content = file.read()

    str = '\n' + str

    keyword = '<head>'
    post = content.find(keyword)
    if post != -1:
        content = content[:post + len(keyword)] + str + content[post + len(keyword):]

    file = open(filePath, 'w', encoding='utf-8')
    file.write(content)
    file.close()

def InsertBody(filePath):
    str = r'''<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5T3Q7M9"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->'''

    file = open(filePath, 'r', encoding='utf-8')
    content = file.read()

    str = '\n' + str
    keyword = '<body>'
    post = content.find(keyword)
    if post != -1:
        content = content[:post + len(keyword)] + str + content[post + len(keyword):]

    file = open(filePath, 'w', encoding='utf-8')
    file.write(content)
    file.close()

四 完整代码

附上完整代码,供参考

from pathlib import Path
import re
import tkinter as tk
from tkinter.filedialog import *
import tkinter.messagebox


def GetAllFile(outputFilePath):
    p = Path(outputFilePath)  # 初始化构造Path对象

    FileList = list(p.glob("**/*.aspx"))  # 得到所有的markdown文件

    #for file in FileList:
        #print(file)

    return FileList


def AddTextToFile(FileList):
    for file in FileList:
        InsertHead(file)
        InsertBody(file)



def InsertHead(filePath):
    str = r'''<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-5T3Q7M9');</script>
<!-- End Google Tag Manager -->'''

    file = open(filePath, 'r', encoding='utf-8')
    content = file.read()

    str = '\n' + str

    keyword = '<head>'
    post = content.find(keyword)
    if post != -1:
        content = content[:post + len(keyword)] + str + content[post + len(keyword):]

    file = open(filePath, 'w', encoding='utf-8')
    file.write(content)
    file.close()


def InsertBody(filePath):
    str = r'''<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5T3Q7M9"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->'''

    file = open(filePath, 'r', encoding='utf-8')
    content = file.read()

    str = '\n' + str
    keyword = '<body>'
    post = content.find(keyword)
    if post != -1:
        content = content[:post + len(keyword)] + str + content[post + len(keyword):]

    file = open(filePath, 'w', encoding='utf-8')
    file.write(content)
    file.close()


def selectFile():
    filepath = askopenfilename()  # 选择打开什么文件,返回文件名
    return filepath

def outputFile():
    outputFilePath = askdirectory()  # 选择目录,返回目录名
    #print(outputFilePath)
    return outputFilePath


def TKShow():
    window = tk.Tk()
    window.title("插入导航内容")
    window.geometry("500x150+650+300")
    window.resizable(False, False)

    # 设置回调函数
    def callback():
        #打开文件对话框
        filePath = outputFile()
        #显示在entry上
        entry.delete(0,'end')
        entry.insert(0,filePath)

    def callback2():
        #获取所有文件路径
        filePath = entry.get()
        fileList = GetAllFile(filePath)
        AddTextToFile(fileList)
        Message("写入完毕!")


    # 使用按钮控件调用函数
    button = tk.Button(window, text="选择文件夹", command=callback)
    button.grid(column=0, row=0,padx=10,pady=10)

    entry = tk.Entry(window,width=65)
    entry.grid(column=0, row=1, padx=5, pady=10)

    button2 = tk.Button(window, text="批量写入", command=callback2)
    button2.grid(column=0, row=3, padx=10, pady=10)

    window.mainloop()


def Message(message):
    tk.messagebox.askokcancel(title="提示", message=message)

if __name__ == '__main__':
    TKShow()



def InsertFile():
    with open("C:/Users/Admin/Desktop/python_test/file_1/2.txt", 'rt') as f1:
        content1 = str(f1.readlines())
        tab = re.search('<html>', content1)
        pos = tab.start()
        #print(pos)

    insert = input("输入要插入的内容:")
    with open("C:/Users/Admin/Desktop/python_test/file_1/2.txt", "w+") as f2:
        content2 = content1[:pos + 1] + insert + content1[pos + 1:]
        #print(content2)
        f2.writelines(content2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值