展开全部
import re
import os
def get_file_list(folder):
file_list = [];
for root, dirs, files in os.walk(folder):
for f in files:
path=root+os.path.sep+f
file_list.append(path)
return file_list
def get_re_file_list(file_list,re_rule):
file_list_re=[]
for file_path in file_list:
if re.search(re_rule,file_path):
file_list_re.append(file_path)
return file_list_re
def rename_basename(file_list_re,re_rule,new_str):
re_c = re.compile(re_rule)
new_file_list = []
for file_path in file_list_re:
old_base_name=os.path.basename(file_path)
new_base_name=re_c.sub(new_str,old_base_name)
new_full_path=os.path.join(os.path.dirname(file_path),new_base_name)
new_file_list.append (new_full_path)
return new_file_list
def rename_dir(root,new_root,file_list):
new_file_list=[]
re_c = re.compile(root)
for file_path in file_list:
new_file_path=re_c.sub(new_root,file_path)
new_file_list.append(new_file_path)
return new_file_list
def rename2list(old_list,new_list):
for i in range(0,len(old_list)):
os.rename(old_list[i],new_list[i])
def main():
root=r"/home/user1/exp1"
old_dir="exp1"
new_dir=r"exp2"
re_rule="xy_|_nk"
new_str=""
old_file_list=get_file_list(root)
re_file_list=get_re_file_list(old_file_list,re_rule)
new_basename_list=rename_basename(re_file_list,re_rule,new_str)
new_dir_list=rename_dir(old_dir,new_dir,new_basename_list)
rename2list(re_file_list,new_dir_list)
if __name__ == '__main__':
main()