python - Rename multiple files inside multiple folders -
so have lot of folders name. in each folder have +200 items. items inside folders has names like:
ct.34562346.246.dcm rd.34562346.dcm rn.34562346.lao.dcm and along style.
i wish rename files inside folders number (34562346) replaced name of folder. example in folder named "1" files inside should become:
ct.1.246.dcm rd.1.dcm rn.1.lao.dcm so large number replaced. , yes, files similar this. number after first . should renamed.
so far have:
import os base_dir = "foo/bar/" #in dir have folders dir_list = [] dirname in os.walk(base_dir): dir_list.append(dirname[0]) this 1 lists entire paths of folders.
dir_list_split = [] name in dir_list[1:]: #the 1 because lists base_dir x = name.split('/')[2] dir_list_split.append(x) this 1 extracts name of each folder.
and next thing enter folders , rename them. , i'm kind of stuck here ?
the pathlib module, new in python 3.4, overlooked. find makes code simpler otherwise os.walk.
in case, .glob('**/*.*') looks recursively through of folders , subfolders created in sample folder called example. *.* part means considers files.
i put path.parts in loop show pathlib arranges parse pathnames you.
i check string constant '34562346' in correct position in each filename first. if replace items .parts next level of folder 'up' folders tree.
then can replace rightmost element of .parts newly altered filename create new pathname , rename. in each case display new pathname, if appropriate create one.
>>> pathlib import path >>> os import rename >>> path in path('example').glob('**/*.*'): ... path.parts ... if path.parts[-1][3:11]=='34562346': ... new_name = path.parts[-1].replace('34562346', path.parts[-2]) ... new_path = '/'.join(list(path.parts[:-1])+[new_name]) ... new_path ... ## rename(str(path), new_path) ... else: ... 'no change' ... ('example', 'folder_1', 'id.34562346.6.a.txt') 'example/folder_1/id.folder_1.6.a.txt' ('example', 'folder_1', 'id.34562346.wax.txt') 'example/folder_1/id.folder_1.wax.txt' ('example', 'folder_2', 'subfolder_1', 'ty.34562346.90.py') 'example/folder_2/subfolder_1/ty.subfolder_1.90.py' ('example', 'folder_2', 'subfolder_1', 'tz.34562346.98.py') 'example/folder_2/subfolder_1/tz.subfolder_1.98.py' ('example', 'folder_2', 'subfolder_2', 'doc.34.34562346.implication.rtf') 'no change'
Comments
Post a Comment