在一个文件夹中,我有100个文件的扩展名为“ .txt”,“。doc”,“。pdf”。我需要将文件重命名为:
到目前为止,我已经尝试过这个
import os,sys
folder ="C:/Users/TestFolder"
for filename in os.listdir(folder):
base_file, ext = os.path.splitext(filename)
print(ext)
if ext == '.txt':
print("------")
print(filename)
print(base_file)
print(ext)
os.rename(filename, base_file + '.jpg')
elif ext == '.doc':
print("------")
os.rename(filename, base_file + '.mp3')
elif ext == '.pdf':
print("------")
os.rename(filename, base_file + '.mp4')
else:
print("Not found")
答案 0 :(得分:0)
首先,您可以将映射存储在字典中,然后在遍历文件夹时找到扩展名,只需使用映射来创建新文件名并保存。
import os
folder ="C:/Users/TestFolder"
#Dictionary for extension mappings
rename_dict = {'txt': 'jpg', 'doc': 'mp3', 'pdf': 'mp4'}
for filename in os.listdir(folder):
#Get the extension and remove . from it
base_file, ext = os.path.splitext(filename)
ext = ext.replace('.','')
#If you find the extension to rename
if ext in rename_dict:
#Create the new file name
new_ext = rename_dict[ext]
new_file = base_file + '.' + new_ext
#Create the full old and new path
old_path = os.path.join(folder, filename)
new_path = os.path.join(folder, new_file)
#Rename the file
os.rename(old_path, new_path)