python: rename files in subfolders by subfolder name

Viewed 1312

I have a folder with lots of subfolders. Eash of subfolders has different type of files. I'm trying to rename those files by the subfolder name they are in ( the won't be duplicates as each file has it's own extension). Data looks like this:

folder
        \ sub1
        \ sub1\file1.ext1
        \ sub1\file2.ext2
        .
        .
        .
        \ sub2
        \ sub2\file1.ext1
        \ sub2\file2.ext2

Desired output

  folder
    \ sub1
    \ sub1\sub1.ext1
    \ sub1\sub1.ext2
    .
    .
    .
    \ sub2
    \ sub2\sub2.ext1
    \ sub2\sub2.ext2

`

My bit of code which doesn't work.

import os

dir_name = os.getcwd() 

for root, dirs, files in os.walk(dir_name, topdown=False):
    for file in files:
        file_name = os.path.splitext(file)[0]#file name no ext
        os.rename(os.path.splitext(file)[0], root ) 

Any ideas? thank you.

1 Answers
Related