Skip to content
Advertisement

How to rename all files to include the directory name?

I’m trying to use a For loop in the code below to go through a list of files and rename them with the file directory’s name.

import re           # add this to your other imports
import os

for files in os.walk("."):
    for f_new in files:
                    folder = files.split(os.sep)[-2]
                    print(folder)   
                    name_elements = re.findall(r'(Position)(d+)', f_new)[0]
                    name = name_elements[0] + str(int(name_elements[1]))
                    print(name)       # just for demonstration
                    dst = folder + '_' + name
                    print(dst)
                    os.rename('Position014 (RGB rendering) - 1024 x 1024 x 1 x 1 - 3 ch (8 bits).tif', dst)

Advertisement

Answer

Use pathlib

  • Path.rglob: This is like calling Path.glob() with '**/' added in front of the given relative pattern:
  • .parent or .parents[0]: An immutable sequence providing access to the logical ancestors of the path
    • If yo want different parts of the path, index parents[] differently
      • file.parents[0].stem returns 'test1' or 'test2' depending on the file
      • file.parents[1].stem returns 'photos'
      • file.parents[2].stem returns 'stack_overflow'
  • .stem: The final path component, without its suffix
  • .suffix: The file extension of the final component
  • .rename: Rename this file or directory to the given target
  • The following code, finds only .tiff files. Use *.* to get all files.
  • If you only want the first 10 characters of file_name:
    • file_name = file_name[:10]
form pathlib import Path

# set path to files
p = Path('e:/PythonProjects/stack_overflow/photos/')

# get all files in subdirectories with a tiff extension
files = list(p.rglob('*.tiff'))

# print files example
[WindowsPath('e:/PythonProjects/stack_overflow/photos/test1/test.tiff'), WindowsPath('e:/PythonProjects/stack_overflow/photos/test2/test.tiff')]

# iterate through files
for file in files:
    file_path = file.parent  # get only path
    dir_name = file.parent.stem  # get the directory name
    file_name = file.stem  # get the file name
    suffix = file.suffix  # get the file extension
    file_name_new = f'{dir_name}_{file_name}{suffix}'  # make the new file name
    file.rename(file_path / file_name_new)  # rename the file


# output files renamed
[WindowsPath('e:/PythonProjects/stack_overflow/photos/test1/test1_test.tiff'), WindowsPath('e:/PythonProjects/stack_overflow/photos/test2/test2_test.tiff')]
Advertisement