文件夹A里面有一批文件的名称为:xy_abc_rnk.mol, xy_abec_rnk.mol, xy_adsdfop_rnk.mol...等类似这样的文件,如何编写代码实现将A文件夹里面的文件名称都改为abc.mol, abec.mol, adsfop.mol...(去掉名称前的xy_和名称后_rnk)并将这些改名后的文件放到B文件夹里面。
2 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
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() |
墨色风雨
TA贡献1853条经验 获得超6个赞
#!/usr/bin/env python
# coding: utf-8
import
os
import
re
import
glob
import
shutil
for
file
in
glob.glob(
'./a/*.mol'
):
basefile
=
os.path.basename(
file
)
_, name, _ , ext
=
re.split(
'_|\.'
, basefile)
shutil.move(
file
,
'./b/%s.%s'
%
(name, ext))
添加回答
举报
0/150
提交
取消