Skip to content Skip to sidebar Skip to footer

Rename A Files Within A Folder Of A Folder To Its Parent Folder?

I have a batch of folders that have a name based on the date. Each folder has a folder where they have file names which are all the same. Is there a way rename the files so they b

Solution 1:

Here is one-way using pathlib from python 3.4+ and f-strings from python 3.6+

first you need to set your path at the top-level directory, so we can recursively find all the csv files and rename with a simple for loop.

from pathlib import Path

files = Path(r'C:\Users\datanovice\Documents\Excels').rglob('*.csv')
# remove 'r' string if you're on macos.for file in files:
    parent_1 = file.parent.name
    parent_2 = file.parent.parent.name
    file.rename(Path(file.parent,f"{parent_1}_{parent_2}{file.suffix}"))
    print(f"{file.name} --> {parent_1}_{parent_2}{file.suffix}")
#1.csv --> ABC_1_2_2019.csv#1.csv --> ABC_2_2_2019.csv

result

for f in files:
    print(f)
C:\Users\datanovice\Documents\Excels\1_2_2019\ABC\1.csvC:\Users\datanovice\Documents\Excels\2_2_2019\ABC\1.csv#after
for f in files:
    print(f)
C:\Users\datanovice\Documents\Excels\1_2_2019\ABC\ABC_1_2_2019.csvC:\Users\datanovice\Documents\Excels\2_2_2019\ABC\ABC_2_2_2019.csv

Post a Comment for "Rename A Files Within A Folder Of A Folder To Its Parent Folder?"