When I use shutil.move() it deletes one folder

Viewed 55

I have a series of files hosted inside another file. These files refer to various cooking dishes and are housed in a file called 'cocina'. I attach the image:

dishes

What I would like to do is to move all the files that have the name "carnes-meat_type" to another folder, hosted in the same place, to be called 'carnes'. However, when I use shutil.move, I don't know why but the file with name "carnes-anade" disappears and only the content of this one appears. I add an image to make it easier to understand:

meats

As you can see in the image, the file (which I have called 'carnes') contains all the folders referring to the type of meats and two .txt files. These two files are the ones that were inside the folder "carnes-anade", and I don't understand why this folder has disappeared and only its files have remained when the only thing I have done was to move the folders of place.

I add the code that I have used:

import re
import os
import shutil

for root, dirs, files in os.walk(root_path):
    for dire in dirs:
        if re.findall(r'carnes-', dire):
            shutil.move(os.path.join(root_path, dire),
                            os.path.join(root_path, 'carnes'))

Where "root_path" refers to the main folder, that is, to 'cocina', which is where the other folders of food dishes are located. What I have done is to search through the re.findall() function for all the files that had the string "carnes-" and moved them to the "carnes" folder, which is created directly once I run the code.

Does anyone know what could be happening?

Thanks in advance.

1 Answers

Take a look at the shutil.move documentation.

When you try to move /a to /b before /b exists, /a gets simply renamed to /b. Afterwards, /c will be moved into /b.

An easy fix is to make sure the destination directory exists, before you move other directories into it.


Example:

Before

cocina
    ├── arroces
    ├── carnes-ave
    │   └── ave.txt
    └── carnes-cabrito
        └── cabrito.txt
import os
import shutil

root_path = "/Users/ptts/test/cocina"
source_dirs = [
    os.path.join(root_path, item)
    for item in os.listdir(root_path)
    if os.path.isdir(os.path.join(root_path, item))
]
destination_dir = os.path.join(root_path, "carnes")

os.makedirs(destination_dir, exist_ok=True)
for source_dir in source_dirs:
    folder_name = os.path.basename(source_dir)
    if folder_name.startswith("carnes-"):
        print("Moving " + source_dir + " to " + destination_dir)
        shutil.move(source_dir, destination_dir)

After

cocina
    ├── arroces
    └── carnes
        ├── carnes-ave
        │   └── ave.txt
        └── carnes-cabrito
            └── cabrito.txt
Related