修改文件后缀名
1 # -*- coding: utf-8 -*- 2 3 import os 4 5 # # 列出当前目录下所有的文件 6 # filedir = 'C:\\Users\\WT\\Desktop\\test' 7 # files = os.listdir(filedir) # 如果path为None,则使用 path = '.' 8 # 9 # for filename in files: 10 # portion = os.path.splitext(filename) # 分离文件名与扩展名 11 # # 如果后缀是jpg 12 # if portion[1] == '.jpg': 13 # # 重新组合文件名与后缀名 14 # newname = portion[0] + '.gif' 15 # filename = filedir + '\\' + filename 16 # newname = filedir + '\\' + newname 17 # os.rename(filename, newname) 18 19 20 def replace_suffix(filedir, suffix): 21 files = os.listdir(filedir) 22 num = 0 23 for filename in files: 24 portion = os.path.splitext(filename) 25 26 if portion[1] != suffix: 27 newname = portion[0] + suffix 28 filename = filedir + '\\' +filename 29 newname = filedir + '\\' +newname 30 os.rename(filename, newname) 31 print("替换文件后缀", filename) 32 num = num + 1 33 print(num) 34 35 36 37 if __name__ == '__main__': 38 replace_suffix('C:\\Users\\WT\\Desktop\\test', '.lay')