当前文件夹下,把所有文件名中的“50076“替换成”50092“,用python实现,代码所下:
# encoding: utf-8
import os
import os.path
curDir = os.getcwd()
oldId = "50076"
newId = "50092"
for parent, dirnames, filenames in os.walk(curDir):
for filename in filenames:
if filename.find(oldId)!=-1:
newName = filename.replace(oldId, newId)
print(filename, "---->", newName)
os.rename(os.path.join(parent, filename), os.path.join(parent, newName))
os.system("pause")
附:遍历特定文件夹中的文件以及子文件夹,代码如下:
# encoding: utf-8
import os
import os.path
rootdir = r'D:\game' # 指明被遍历的文件夹
#三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
for parent, dirnames, filenames in os.walk(rootdir):
for dirname in dirnames: #输出文件夹信息
print "parent is: " + parent
print "dirname is: " + dirname
for filename in filenames: #输出文件信息
print "parent is: " + parent
print "filename is: " + filename
print "the full name of the file is: " + os.path.join(parent,filename) #输出文件路径信息