一。import os
os.rename(src, dst)
比如要把d:\test.py重新命名为d:\tt.py
import os
os.rename('d://test.py','d://tt.py')
记得写绝对路径哦
二。
#! /usr/bin/env python
import sys, string, os
for root, dir, files in os.walk(sys.argv[1]):
for file in files:
newname = string.join(string.split(file, sys.argv[2]), sys.argv[3])
newpath = sys.argv[1] + newname
oldpath = sys.argv[1] + file
try:
os.rename(oldpath, newpath)
except ValueError:
print "Error when rename the file " + oldpath
except NameError:
print "Error when rename the file " + oldpath
except OSError:
print newpath + " The file is already exist!"
然后:
rn.py path src_string dst_string
如:
[williamx@william3 test]$ ls
789.tt ok789s.t ok789s1.t ok789s1.t2 rn.py rn.py~
[williamx@william3 test]$ rn.py ./ 789 456
[williamx@william3 test]$ ls
456.tt ok456s.t ok456s1.t ok456s1.t2 rn.py rn.py~