import os
def swap_extensions(dir, before, after):
if before[:1] != '.': #如果参数中的后缀名没有'.'则加上
before = '.' + before
thelen = -len(before)
if after[:1] != '.':
after = '.' + after
for path, subdir, files in os.walk(dir):
for oldfile in files:
if oldfile[thelen:] == before:
oldfile = os.path.join(path, oldfile)
newfile = oldfile[:thelen] + after
os.rename(oldfile, newfile)
print oldfile +' changed to ' + newfile
if __name__ == '__main__':
import sys
if len(sys.argv) != 4:
print 'Usage:swap_extension.py rootdir before after'
sys.exit(1)
swap_extensions(sys.argv[1], sys.argv[2], sys.argv[3])
例子:将e:/py/test目录下.php结尾的文件重命名为.py
E:py>python_cook e:/py/test .php .py
e:/py/testtest.php changed to e:/py/testtest.py
e:/py/test1.php changed to e:/py/test1.py
e:/py/test2.php changed to e:/py/test2.py
希望本文所述对大家的Python程序设计有所帮助。