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.

JavaScript

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]
JavaScript
Advertisement