参考代码注释
import os
from tkinter import filedialog
import tkinter as tk
from tkinter import Button
class ReName():
def __init__(self):
self.n = 0
def shouldIgnore(self, path: str) -> bool:
'''忽略以下路径:
1. 文件夹。
2. macOS 隐藏文件
a. 文件名以 '.' 开头,如 ".git"。
b. 文件被设置了隐藏属性。
'''
import stat
m = os.stat(path).st_mode
if stat.S_ISDIR(m):
return True
if path.startswith('.'):
return True
if m & stat.FILE_ATTRIBUTE_HIDDEN:
return True
return False
def rename(self):
file_path = filedialog.askdirectory(title='ReNamer')
file_lists = os.listdir(file_path)
for file in file_lists.copy():
oldname = file_path + os.sep + file
# 筛选除了文件夹,还有隐藏文件。
# if os.path.isdir(oldname):
if self.shouldIgnore(oldname):
continue
else:
newname = file_path + os.sep + \
'(' + str(self.n + 1) + ')' + file
print(f'rename {oldname} to {newname}')
self.n += 1
print(self.n)
root = tk.Tk()
root.geometry("550x200")
label = tk.Label(root, font=("Arial Bold", 15),
text='Please select a directory to rename files in the folder:')
label.pack()
ins = ReName()
# command 参数应该是个函数。
#btn=Button(root,font=("Arial",15),bg='orange',text="Click Me",command=ins.rename())
btn = Button(root, font=("Arial", 15), bg='orange',
text="Click Me", command=ins.rename)
btn.pack()
print(ins.n)
label = tk.Label(root, text=str(ins.n)+' file(s) renamed.')
label.pack()
root.mainloop()