最近在继续提高自己的go技术时,从网上一些平台获取到了一些学习资料,然后下载到本地后,文件的命名是真的像衣托答辩:

image-20230921194855810

除了上述的文件,还有一mol多神奇的命名,害,由于资料是从小道途径获得的,咱就忍了。接下来就是要批量对这些文件改名的问题,我粗略算了下,有上千个的文件需要改。对于程序员来说,总不能挨个挨个文件重命名吧,于是我就写了两个脚本,一个python版本,一个go版本,均能批量对文件夹及其子文件夹里的文件进行批量重命名,去掉烦人的”信息”,亲测体检较好。

下面附上两个版本的代码:

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os

# 要处理的根文件夹路径
root_folder = '/path/to/your/root/folder'

# 要去掉的字符串
string_to_remove = "【加微信.赠送精品IT课程】"

# 遍历根文件夹及其子文件夹
for folder_path, _, file_names in os.walk(root_folder):
for file_name in file_names:
file_path = os.path.join(folder_path, file_name)
# 检查文件名是否包含要去掉的字符串
if string_to_remove in file_name:
# 构建新的文件名,去掉特定字符串
new_file_name = file_name.replace(string_to_remove, "")
new_file_path = os.path.join(folder_path, new_file_name)
# 重命名文件
os.rename(file_path, new_file_path)
print(f"重命名文件:{file_path} -> {new_file_path}")

Go:

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
36
37
38
39
40
41
42
43
44
45
46
package main

import (
"fmt"
"os"
"path/filepath"
"strings"
)

func main() {
// 要处理的根文件夹路径
rootFolder := "/path/to/your/root/folder"

// 要去掉的字符串
stringToRemove := "【加微信.赠送精品IT课程】"

// 遍历根文件夹及其子文件夹
err := filepath.Walk(rootFolder, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}

// 只处理文件
if !info.IsDir() {
// 检查文件名是否包含要去掉的字符串
if strings.Contains(info.Name(), stringToRemove) {
// 构建新的文件名,去掉特定字符串
newFileName := strings.Replace(info.Name(), stringToRemove, "", -1)
newFilePath := filepath.Join(filepath.Dir(path), newFileName)

// 重命名文件
err := os.Rename(path, newFilePath)
if err != nil {
fmt.Printf("重命名文件失败:%s -> %s, 错误:%v\n", path, newFilePath, err)
} else {
fmt.Printf("重命名文件成功:%s -> %s\n", path, newFilePath)
}
}
}
return nil
})

if err != nil {
fmt.Printf("遍历文件夹时发生错误:%v\n", err)
}
}

附上一张代码运行结果图,可以看到重命名了many的文件:

image-20230921195711006

通过上述操作,我的项目文件就完美了,命名也都正常了:

image-20230921195749766

nice~

继续学习~