语法
rename()方法语法格式如下:
os.rename(src, dst)
参数
-
src -- 要修改的目录名
-
dst -- 修改后的目录名
返回值
该方法没有返回值
实例1
import os
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
path = input("请输入需要重命名的目录")
listdir = os.listdir(path)
for i in listdir:
if ".xml" in i: #限定xml文件
oldpath = os.path.join(path,i) #os.path.join(a,b)用于拼接路径
tree = ET.parser(oldpath)
filename = tree.find("filename").text
newpath = os.path.join(path,filename)
print("filename",filename)
print("oldpath:"+oldpath,"newpath:"+newpath)
os.rename(oldpath,newpath)
'''呈现的效果是把path目录下的子目录xml文件循环访问,并用其中的filename节点的值重命名文件。'''
实例2
'''用指定的规则给target目录下的子目录重命名可以用os.walk'''
import os
def walk(path,pj_str):
for root, dirs, files in os.walk(path):
for file in files:
#获取完整路径
all_path = os.path.join(root,file)
print(all_path,"allpath")
allpath_list = all_path.split("\\")
filename = allpath_list[-1]
pjlist = pj_str.split(" ")
print(len(pjlist))
new_filename = allpath_list[int(pjlist[0])]+"-"+allpath_list[int(pjlist[1])]+"-"+allpath_list[int(pjlist[2])]+"-"+allpath_list[int(pjlist[3])]+"-"+filename
newall_path = os.path.join(root,new_filename)
print(all_path,"allpath")
print(newall_path,"newallpath")
print(root,"root?")
# os.rename(all_path,newall_path)
path = input("请输入你要重命名的目录 ")
pj_str = input("请输入拼接规则:")
walk(path,pj_str)