批量添加和修改文件拓展名

当你拿到了大批量的文件,但是文件拓展名却因为各种原因出了 bug,那么此时用代码批量处理肯定比手敲要效率高的多

批量添加文件拓展名

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
import os

def add_extension_to_files(directory, extension):
"""
遍历指定目录,为每个文件添加扩展名。

:param directory: 要遍历的目录路径
:param extension: 要添加的扩展名(包括点,例如 '.txt')
"""
# 检查目录是否存在
if not os.path.exists(directory):
print("指定的目录不存在")
return

# 遍历目录中的所有文件
for filename in os.listdir(directory):
# 获取文件的完整路径
file_path = os.path.join(directory, filename)
# 检查是否为文件
if os.path.isfile(file_path):
# 获取不带扩展名的文件名
name, _ = os.path.splitext(file_path)
# 构造新的文件名并添加扩展名
new_file_path = f"{name}{extension}"
# 重命名文件
os.rename(file_path, new_file_path)
print(f"文件 {filename} 已重命名为 {new_file_path}")

# 使用示例
directory_path = 'D:/example' # 替换为你的目录路径
extension_to_add = '.zip' # 你想要添加的扩展名
add_extension_to_files(directory_path, extension_to_add)

批量修改文件拓展名

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
import os

def rename_extension(directory, old_extension, new_extension):
"""
遍历指定目录,将所有指定扩展名的文件批量修改为新的扩展名。

:param directory: 要遍历的目录路径
:param old_extension: 原始扩展名(包括点,例如 '.txt')
:param new_extension: 新扩展名(包括点,例如 '.md')
"""
# 检查目录是否存在
if not os.path.exists(directory):
print("指定的目录不存在")
return

# 遍历目录中的所有文件
for filename in os.listdir(directory):
# 获取文件的完整路径
file_path = os.path.join(directory, filename)
# 检查是否为文件且具有指定的原始扩展名
if os.path.isfile(file_path) and filename.endswith(old_extension):
# 获取不带扩展名的文件名
name, _ = os.path.splitext(file_path)
# 构造新的文件名并添加新扩展名
new_file_path = f"{name}{new_extension}"
# 重命名文件
os.rename(file_path, new_file_path)
print(f"文件 {filename} 已重命名为 {new_file_path}")

# 使用示例
directory_path = 'D:/example' # 替换为你的目录路径
old_extension = '.zip' # 你想要替换的原始扩展名
new_extension = '.md' # 你想要替换成的新扩展名
rename_extension(directory_path, old_extension, new_extension)