Move subfolders with python

Asked

Viewed 179 times

1

Some time ago I was trying to create a script Python to move subdirectories from one folder to another for example:

root  
├── pasta1  
│   ├── pastaa  
│   └── pastab  
├── pasta2  
└── pasta3  
    ├── pastac  
    └── pastad  

I have been trying unsuccessfully to get my python script to search the subdirectories of my folder root being the folders "pasture, pastab, pastac and pastad" were moved a directory above the root directory. any idea?

  • Can you enter the relevant code that has worked so far? This helps to help you

1 answer

1

You can use pathlib.Path to browse the folders and pathlib.Path.rename to move its contents to the root folder.

Take an example:

from pathlib import Path

# path da pasta root
root = Path('./root')
subpasta = Path('./root/pasta_1/subpasta_a')

# dados
print(root)                  # 'root'
print(subpasta)              # 'root/pasta_1/subpasta_a'
print(subpasta.name)         # 'subpasta_a'
print(root / subpasta.name)  # 'root/subpasta_a'

# move subpasta para './root/subpasta_a'
subpasta.rename(root / subpasta.name)

In the example above I use pathlib.Path to create a path to the folder root and for the sub-folder root/pasta_1/subpasta_a, then print some data to demonstrate the use of Path.name to take the directory name and use of the operator / to join two paths (see PEP-0428 for more information). And finally, I use these concepts together with the method Path.rename to move the subfolder to the root folder.

Applying the above concepts to your problem, just iterate in the directory using Path.iterdir and use Path.is_dir to test whether the iterated item is a folder and move its contents to root.

Final code

from pathlib import Path

# Pasta raiz
root = Path('./root')

# Percorre os arquivos e pastas do diretório `root`
for item in root.iterdir():
    if item.is_dir():
        # Percorre as subpastas de root (`pasta_1`, `pasta_2` e `pasta_3`)
        for subitem in item.iterdir():
            # Move o arquivo/pasta para o root
            subitem.rename(root / subitem.name)

Commonly the module os is used for this type of operation (such as @jsbueno you mentioned in one comment), however the module pathlib includes some common operations of the module os as rename, unlink, mkdir (among others).

In this case I’m using for the ease of the Path, do not know the implementation of Cpython to state if there is any performance impact. You can also use the function os.scandir to go through the items in a directory, as its documentation states that it is more performative than os.listdir, but I do not know if this function is more performative than Path.iterdir or os.walk.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.