Rename multiple files inside multiple folders

前端 未结 3 544
一整个雨季
一整个雨季 2021-01-24 01:50

So I have a lot of folders with a certain name. In each folder I have +200 items. The items inside the folders has names like:

CT.34562346.246.dcm
RD.34562346.dc         


        
3条回答
  •  执念已碎
    2021-01-24 02:15

    The pathlib module, which was new in Python 3.4, is often overlooked. I find that it often makes code simpler than it would otherwise be with os.walk.

    In this case, .glob('**/*.*') looks recursively through all of the folders and subfolders that I created in a sample folder called example. The *.* part means that it considers all files.

    I put path.parts in the loop to show you that pathlib arranges to parse pathnames for you.

    I check that the string constant '34562346' is in its correct position in each filename first. If it is then I simply replace it with the items from .parts that is the next level of folder 'up' the folders tree.

    Then I can replace the rightmost element of .parts with the newly altered filename to create the new pathname and then do the rename. In each case I display the new pathname, if it was appropriate to create one.

    >>> from pathlib import Path
    >>> from os import rename
    >>> for 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'
    

提交回复
热议问题