0

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)
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
AA2018-2020
  • 341
  • 1
  • 6
  • 16
  • 4
    Are you aware that renaming them from .tif to .png won't actually change their format, and will likely confuse programs that expect a .png file to actually contain PNG data? – Bryan Oakley Jun 28 '20 at 22:14
  • Thanks for your comment. That should be fine. As they file swill need to go into another application which expect them to be in a png format. – AA2018-2020 Jun 28 '20 at 22:17
  • 2
    @AA2018-2020 - The (other) application is expecting files in PNG format, or file with a `.png` file extension? These are very different things. Anyhow, why not just write a **simple shell script** to do the rename job? – S3DEV Jun 28 '20 at 22:29
  • ... if you require Python, have a look at the `os.path.splitext()` function. It’ll make life a lot easier for you. – S3DEV Jun 28 '20 at 22:31
  • @S3DEV I have more than one folder with similar file names. This code rename the files with the name directory, which is helpful to avoid files with the same name. The application expect then in .png. – AA2018-2020 Jun 28 '20 at 22:50
  • If the file expects them to be in png format, renaming them will not do that. You must perform a conversion of the data, much like if you have a file written in English, just changing the name of the file won't transform it into French or Spanish. – Bryan Oakley Jun 28 '20 at 22:58
  • @BryanOakley Thanks for clarifying this. I have amended my question. I am now interested in changing the file name only. I will deal with changing the file format in a different way. – AA2018-2020 Jun 28 '20 at 23:08
  • Is this really how your code looks? There's some broken indentation that needs to be addressed. – Bryan Oakley Jun 28 '20 at 23:17
  • @BryanOakley I have altered the code so the indentation error is no longer appearing but now i get an error regarding IndexError: list index out of range – AA2018-2020 Jun 28 '20 at 23:39

1 Answers1

3

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')]
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158