代码示例如下:
1 #!/usr/local/bin python 2 import os 3 def swapextensions(dir, before, after): 4 if before[:1] != '.': 5 before = '.'+before 6 thelen = -len(before) 7 if after[:1] != '.': 8 after = '.'+after 9 for path, subdir, files in os.walk(dir): 10 for oldfile in files: 11 if oldfile[thelen:] == before: 12 oldfile = os.path.join(path, oldfile) 13 newfile = oldfile[:thelen] + after 14 os.rename(oldfile, newfile) 15 16 if __name__ == '__main__': 17 import sys 18 if len(sys.argv) != 4: 19 print "Usage: swapext rootdir before after" 20 sys.exit(100) 21 swapextensions(sys.argv[1], sys.argv[2], sys.argv[3])
可在命令行模式下根据参数进行需要更改替换的后缀!
与大家共勉!