之前用Python编写过批量修改文件名的脚本程序,代码很简单,运行也比较快,唯一美中不足之处是每次批量修改文件名时都需要执行以下步骤:
1)复制文件夹路径;
2)打开脚本程序
3)替换脚本中的文件夹路径
4)保存脚本程序
5)执行脚本程序
为了便于操作,最好还是弄成GUI界面,手动选择文件夹,这样程序也更通用。Python中的GUI库很多,绝大部分都支持跨平台,其中安装python时自带的GUI库是tkinter,本文就学习并创建基于tkinte的批量修改文件名程序。
本文涉及的知识点包括以下几个:
1)使用tkinter.Tk创建窗口,并且调用geometry函数设置窗口的宽和高,需要注意的是geometry函数接收的是字符串,宽度x高度,中间的乘号其实是小写的x,用数学符号或者是大写的X会报错;
2)布局方式:根据参考文献1,tkinter有pack、grid、place三种布局方式,本文采购grid布局方式,该方式有点类似Winfom中的TableLayoutPanel,不同之处在于不用提前设置好行数和列数,只需指定所用控件的行号和列号即可;
3)控件,主要使用了标签(tkinter.Label)、文本(tkinter.Entry)、按钮(tkinter.Button)控件,tkinte通过变量绑定的方式获取或更新文本控件的值。
4)浏览文件夹,根据参考文献2,调用tkinter.filedialog中的askdirectory()选择文件夹。
全部代码如下所示:
# coding=gbk
import tkinter as tk
import os
from tkinter.filedialog import askdirectory
def BrowseDri():
txtDirPath.set(askdirectory())
def BatchReplaceFileName():
path = txtDirPath.get()
strSign=txtRemovedContent.get()
files=os.listdir(path)
for onefile in files:
if onefile.find(strSign)<0:
continue
oldname=path+"\\"+onefile
newname=path+"\\"+onefile.replace(strSign,"")
os.rename(oldname,newname)
print(oldname,"====>",newname)
window=tk.Tk()
window.title('批量处理文件名')
window.geometry('600x400')
tk.Label(window,text='选择文件夹').grid(row=0,column=0)
txtDirPath=tk.StringVar()
tk.Entry(window,textvariable=txtDirPath).grid(row=0,column=1)
tk.Button(window,text='浏览',command=BrowseDri).grid(row=0,column=2)
tk.Label(window,text='输入要移除的内容:').grid(row=1,column=0)
txtRemovedContent=tk.StringVar()
tk.Entry(window,textvariable=txtRemovedContent).grid(row=1,column=1)
tk.Button(window,text='移除',command=BatchReplaceFileName).grid(row=1,column=2)
tk.mainloop()
最后是程序运行效果,如下面几张截图所示:运行程序后,首先选择要批量处理的文件夹,然后设置文件名中要移除的内容,最后点击移除按钮批量处理文件名。
参考文献
[1]Python从菜鸟到高手
[2]https://blog.youkuaiyun.com/weixin_41967600/article/details/124498027