0

I have a folder structure like this:

C:\Users\me\JupyterNotebooks\Work\LabCode\datafiles\2020_09sept_17\00\58

Under the last '58' folder, a file is placed; 00.avro

I would like to rename the file to: 2020_09sept_17_00_58_00.avro (adding the three last directories to the filename)

I am able to rename the filename with the 58 folder, to 58_00.avro:

for root, dirs, files in 
    os.walk(r'C:\Users\me\JupyterNotebooks\Work\LabCode\datafiles\2020_09sept_17\00'):      
    if not files:
        continue
    prefix = os.path.basename(root)
    for f in files:
        os.rename(os.path.join(root, f), os.path.join(root, "{}_{}".format(prefix, f)))

(from this link)

But how to rename with several folder names?

Miss.Pepper
  • 103
  • 10

1 Answers1

0

Try this:

for root, dirs, files in os.walk(r'C:\Users\me\JupyterNotebooks\Work\LabCode\datafiles\2020_09sept_17\00'):      
    if not files:
        continue
    dirnames = []
    pref = root
    for _ in range(3):  # Collect the last 3 dir names
        dirnames.insert(0, os.path.basename(pref))
        pref = os.path.dirname(pref)

    prefix = "_".join(dirnames)
    for f in files:
        current_name = os.path.join(root, f)
        new_name = os.path.join(root, "{}_{}".format(prefix, f))
        os.rename(current_name, new_name)