python去文件名方括号广告

有时候我们从网上下载文件,下载内容提供者会用方括号加注一些网址之类的广告。
而我有一次发现我下载的许多文件都是使用这种加注广告的方式,所以就用python设计了一个自动化去方括号广告的程序。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import os
import tkinter as tk
from tkinter.filedialog import (askopenfilename,
askopenfilenames,
askdirectory,
asksaveasfilename)
#调用系统自带的GUI目录选择界面,选择要去广告的文件的目录。
root = tk.Tk()
pth=askdirectory()
#去广告函数。
def rename(pth):
#对于选定目录的所有文件遍历。
for file in os.listdir(pth):
#拼合为绝对路径。
xfile = os.path.join(pth,file)
#如果是文件夹的话,就再次调用自身函数。
if os.path.isdir(xfile):
rename(xfile)
#如果是文件。
else:
i = None; j = None
#如果文件名里有方括号,标记其位置,并删去方括号及其里的内容。
if ('[' in file and ']' in file):
i = file.index('[')
j = file.index(']')
file = file[:i] + file[j+1:]
if ('【' in file and '】' in file):
i = file.index('【')
j = file.index('】')
file = file[:i] + file[j+1:]
#拼合新文件的绝对路径。
nfile = os.path.join(pth,file)
#重命名
os.rename(xfile,nfile)
rename(pth)

写完了这个程序之后,我又发现了个新问题,就是执行了这段程序后有些文件以点开头,我将在另一篇博文中介绍去点的程序。

(您还可以在归档页搜索文章标题)