Home > Mobile >  problem with moving files with extensions with shutil
problem with moving files with extensions with shutil

Time:10-27

I have the following code that should move files from one directory to another, the problem is when I run the code it just creates the folder and not moving any file to it. can anyone help me with that?

import os
import glob
import shutil

def remove_ext(list_of_pathnames):

return [os.path.splitext(filename)[0] for filename in list_of_pathnames]

 path = os.getcwd()
 os.chdir("D:\\TomProject\\Images\\")   
 os.mkdir("image_with_xml")     # create a new folder
 newpath = os.path.join("D:\\TomProject\\Images\\" ,"image_with_xml") # 
 made it os 
 independent... 

 list_of_jpegs = glob.glob(path "\\*.jpeg")
 list_of_xmls = glob.glob(path "\\*.xml")

 jpegs_without_extension = remove_ext(list_of_jpegs)
 xmls_without_extension = remove_ext(list_of_xmls)

 for filename in jpegs_without_extension:
  if filename in xmls_without_extension:

 shutil.move(filename   '.jpg', newpath) # move image to new path.
 shutil.move(filename   '.xml', newpath)

CodePudding user response:

You first use ".jpeg" as extension but then when you move mistakenly use ".jpg".

CodePudding user response:

this is the code now:

import os
import glob
import shutil

def remove_ext(list_of_pathnames):
"""
 removes the extension from each filename
 """
 return [os.path.splitext(filename)[0] for filename in list_of_pathnames]

path = os.getcwd()
os.chdir("D:\\TomProject\\Images\\")   
os.mkdir("image_with_xml")     # create a new folder
newpath = os.path.join("D:\\TomProject\\Images\\","image_with_xml") # made it os 
 independent... 

 list_of_jpgs = glob.glob(path "\\*.jpg")
 list_of_xmls = glob.glob(path "\\*.xml")

print(list_of_jpgs, "\n\n", list_of_xmls) #remove

jpgs_without_extension = remove_ext(list_of_jpgs)
xmls_without_extension = remove_ext(list_of_xmls)

print(jpgs_without_extension, "\n\n", xmls_without_extension) #remove

for filename in jpgs_without_extension:
 if filename in xmls_without_extension:
    print("moving", filename) #remove
    shutil.move(filename   '.jpg', newpath)  # move image to new path.
    shutil.move(filename   '.xml', newpath)   # move image to new path.

when I run it it prints me this: []

[] []

[] Press any key to continue . . .

  • Related