How to rename all specific filetypes of files within subfolders to name with same file extension but same file name

I have 690 files within subfolders - the subfolders names need to stay the same but the .iso files within each subfolder needs to be renamed to game.iso - this is possible as each ISO is in its own folder (folder name cannot be changed)

I'm currently teaching myself Python3 but I'm really struggling with this.

Any help is appreciated. Cheers.

2 answers

  • answered 2022-01-23 03:00 user517339

    The "newer" pathlib module is helpful here.

    A recursive glob can match all filenames by extension.

    >>> from pathlib import Path
    >>> for p in Path().rglob('*.iso'):
    ...     print(p)
    a/b/2.iso
    a/b/c/d/3.iso
    a/b/c/d/e/1.iso
    

    The part before the extension is called the stem in pathlib terminology - you can modify this using .with_stem()

    >>> for p in Path().rglob('*.iso'):
    ...     print(p.with_stem('game'))
    a/b/game.iso
    a/b/c/d/game.iso
    a/b/c/d/e/game.iso
    

    You can pass this directly to the .rename() method

    for p in Path().rglob('*.iso'):
        p.rename(p.with_stem('game'))
    

    Which will rename all of the files:

    >>> for p in Path().rglob('*.iso'):
    ...     print(p)
    a/b/game.iso
    a/b/c/d/game.iso
    a/b/c/d/e/game.iso
    

  • answered 2022-01-23 03:04 Mario Saraiva

    Here is a script that achieves this. It does so recursively, and you run it by providing the root directory where you want to start working from. For example, I have the script saved as iso_rename: ./iso_rename <enter full path to start lookin for .iso files>

    #!/usr/local/bin/python3
    
    import os, sys
    
    dir = sys.argv[1]
    
    def rename_iso(dir):
      items = os.scandir(dir)
    
      for item in items:
        if item.is_file() and item.name.endswith('.iso'):
          if item.name == 'game.iso':
            continue
          os.rename(item.path, os.path.join(dir, 'game.iso'))
        elif item.is_dir():
          rename_iso(item.path)
    
    rename_iso(dir)
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum