Home > Back-end >  how to copy files with the same name between two folders in python
how to copy files with the same name between two folders in python

Time:11-24

I have a code that move number of files if the files have a specific element in them to dest folder. the problem i have is that the files I move have the same name as the files that do not move to the dest folder, for example:

I have a file named 132918079761502058_40.xml

that the code moves to the dest folder. but also i have the following files that i want to move with it named:

132918079761502058_40.txt
132918079761502058_40.jpeg

I cant figure it out how to move the additional files that have the same name to the dest folder. my code so far is:

    import shutil
    from pathlib import Path
    from xml.etree import ElementTree as ET


    def contains_car(path):
     tree = ET.parse(path.as_posix())
     root = tree.getroot()
     for obj in root.findall('object'):
         rank = obj.find('name').text
         if rank == 'car':           
              return True
     return False
    

    def move_car_files(src="D:\\TomProject\\Images\\", dst="D:\\TomProject\\Done"):
     src, dst = Path(src), Path(dst)
     for path in src.iterdir():
        if path.suffix == '.xml' and contains_car(path):
            print(f'Moving {path.as_posix()} to {dst.as_posix()}')
            shutil.move(path, dst)

    if __name__ == "__main__":
        move_car_files()

i was trying to find an answer in this forum for a while and did not find any directions

CodePudding user response:

After you have moved your main file -- the .xml file, simply look for all the similar files - same name but different suffix - in your src folder. Then move those.

def move_car_files(src="D:\\TomProject\\Images\\", dst="D:\\TomProject\\Done"):
    src, dst = Path(src), Path(dst)
    for path in src.iterdir():
        if path.suffix == '.xml' and contains_car(path):
            print(f'Moving {path.as_posix()} to {dst.as_posix()}')
            shutil.move(path, dst)
            similar_filepaths = [e for e in src.iterdir() if e.stem == path.stem and e.suffix != '.pickle']
            for filepath in similar_filepaths:
                print(f'Moving SIMILAR file -- {filepath.as_posix()} to {dst.as_posix()}')
                shutil.move(filepath, dst)

CodePudding user response:

if path.suffix == '.xml' and contains_car(path):
    wildcard = path.with_suffix("*")
    print(f'Moving {wildcard.as_posix()} to {dst.as_posix()}')
    for file in glob.glob(wildcard):
        shutil.move(file, dst)
  • Related