Search code examples
pythonregeximagejpeglistdir

Iterate over a folder tree and add xmp data to files in folders then move


Im trying to run a python script on a folder that embeds xmp data into images, modifies the filename regex, then moves the files.

It works fine until you place another folder inside the directory, I want to be able to look inside and do the same thing to the images in there.

for fileName in os.listdir(xmpDir):
  if not fileName.startswith('.'):  
    print (fileName)
    pid = re.findall(r'(_ID\d+_)', fileName)                  
    pid2 = str(pid)                                           
    bid = re.sub(r'\D', '', pid2)                              
    bid2 = int(bid)                                            
    newFileName = re.sub(r'(_ID\d+_)', '', fileName) 

    xmpfile = XMPFiles( file_path=fileName, open_forupdate=True )
    xmp = xmpfile.get_xmp()
    xmp.set_property(consts.XMP_NS_DC, u'ID', bid )
    xmpfile.put_xmp(xmp)
    xmpfile.close_file()
    shutil.move(xmpDir + fileName, newPath1 + newFileName)
    finder_colors.set(newPath1 + newFileName, 'purple')

I have tried os walk but it gives me an error, I it is trying to find a regex on the folder.

`DIR
|
+--- [subdir]
|     |
|     +--- image1.jpg
|     +--- image2.jpg
|
+--- [subdir]
|     |
|     +--- image3.jpg
|     +--- image4.jpg
+--- image5.jpg
+--- image6.jpg`

move to

`new dir with xmp
|
+--- [subdir]
|     |
|     +--- image1.jpg
|     +--- image2.jpg
|
+--- [subdir]
|     |
|     +--- image3.jpg
|     +--- image4.jpg
+--- image5.jpg
+--- image6.jpg`

I've hit a bit of a wall any help would be appreciated.

Thanks!


Solution

  • You have to make your function recursive: process all the files in your directory and for every folder you find, call your function again with that folder as a parameter.

    You will also have to adjust the paths in the move functions as they'll change with every function call.