我有两个文件夹,每个文件夹有六个具有不同扩展名(.txt,.jpg,.tiff等)的文件,我想使用Python重命名具有相同名称的每个文件名(不想更改文件扩展名)
请帮帮我。我是编程新手,现在开始学习Python
谢谢。
答案 0 :(得分:0)
尝试一下:-
for filename in os.listdir(folder_name):
src=foldername+filename
dst=new_name+filename.split(".")[1]
dst=folder_name+dst
os.rename(src,dst)
答案 1 :(得分:0)
使用os.listdir列出目录中的所有文件,然后使用os.rename 重命名所有文件,也可以使用os.path.splitext提取扩展名和文件名
import os
folder_name = '<folder_where_we_have_files>'
name = '<name_for_file>'
for file in os.listdir(folder_name):
#Get the full file path
file_path = os.path.join(folder_name, file)
#Get the file name and it's extension
file_name, extension = os.path.splitext(file_path)
#We don't want to rename file which is already renamed
if name not in file_name:
#Create the full path of the new file
new_file = os.path.join(folder_name, name + extension)
#Rename the file to new file
os.rename(file_path, new_file)