import os
def change_file_extension(path, old_ext, new_ext):
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(old_ext):
old_file = os.path.join(root, file)
new_file = os.path.splitext(old_file)[0] + new_ext
os.rename(old_file, new_file)
# 示例:将路径为 "C:\test" 下所有 .txt 文件的后缀修改为 .md
change_file_extension("C:\test", ".txt", ".md")
该函数接受三个参数:文件夹路径、旧后缀和新后缀。它使用 os.walk()
函数遍历文件夹下的所有文件,然后使用 os.path.splitext()
函数获取文件名和旧后缀,再拼接上新后缀,最后使用 os.rename()
函数重命名文件。
os.walk
:是 Python 中用于遍历目录树的函数。它返回一个三元组 (dirpath, dirnames, filenames)
dirpath:当前遍历到的目录的路径
dirnames:当前目录下的所有子目录的名称列表
filenames:当前目录下的所有文件的名称列表
os.walk()
方法会递归遍历目录树,即遍历当前目录及其所有子目录。在遍历过程中,对于每个目录,os.walk() 方法会返回一个三元组,其中包含该目录下的所有子目录和文件的名称列表。