0

I am trying to write a python script so that I can find all sub_directories called 'something' within a parent directory.Then I would like to rename the sub directories and move them somewhere else. So far I have my code as:

import os, shutil,fnmatch

match = {}
for root, dirnames, filenames in os.walk('test'):
    #print root
    #print dirnames
    #print filenames
    for i in fnmatch.filter(dirnames,'find'):
        #print os.path.join(root,dirnames[0])
        print root
        #match.append(root)
        match[root]=dirnames[0]

call match gives me something like {'test\a': 'find'......}. I would like to modify the key value of the dictionary so that it looks like {'a':'find'... so essentially I am trying to get rid of the name of the parent directory. I thought about converting to string and use split but seems to be not so efficient.

Sitz Blogz
  • 1,061
  • 6
  • 30
  • 54
Pupusa
  • 167
  • 1
  • 3
  • 14

1 Answers1

0

To get the dirname without the parent directory name, use os.path.basename, this way:

>>> dirname = 'C:\\Users\\myUsers\\Videos'
>>> os.path.basename(dirname)
'Videos'

EDIT: in response to OP comments,

Given:

dirname = 'C:\\Users\\myUsers\\Videos'

And you want to get new folder name as myUsers_Videos, here is one way:

>>> os.path.basename('_'.join(os.path.split(dirname)))
'myUsers_Videos'
Iron Fist
  • 10,739
  • 2
  • 18
  • 34