Home > Back-end >  Python: recursively move all files from folders and sub folders into a root folder
Python: recursively move all files from folders and sub folders into a root folder

Time:11-21

Given a file tree with much dept like this:

├── movepy.py              # the file I want use to move all other files
└── testfodlerComp
├── asdas
│   └── erwer.txt
├── asdasdas
│   └── sdffg.txt
└── asdasdasdasd
    ├── hoihoi.txt
    ├── hoihej.txt
    └── asd
        ├── dfsdf.txt
        └── dsfsdfsd.txt

How can I then move all items recursively into the current working directory:

├── movepy.py
│── erwer.txt    
│── sdffg.txt
├── hoihoi.txt
├── hoihej.txt
├── dfsdf.txt
└── dsfsdfsd.txt

The file tree in this question is an example, in reality I want to move a tree that has many nested sub folders with many nested files.

CodePudding user response:

This should do the trick for what you're trying to achieve.

import os
import shutil

#store the path to your root directory
base='.'

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk(base):
    path = root.split(os.sep)

    for file in files:
        if not os.path.isdir(file):
            
            # move file from nested folder into the base folder
            shutil.move(os.path.join(root,file),os.path.join(base,file))

CodePudding user response:

import os
import shutil
from pathlib import Path

cwd = Path(os.getcwd())

to_remove = set()
for root, dirnames, files in os.walk(cwd):
    for d in dirnames:
        to_remove.add(root / Path(d))

    for f in files:
        p = root / Path(f)
        if p != cwd and p.parent != cwd:
            print(f"Moving {p} -> {cwd}")
            shutil.move(p, cwd)

# Remove directories
for d in to_remove:
    if os.path.exists(d):
        print(d)
        shutil.rmtree(d)
  • Related