简体   繁体   中英

Python: recursively move all files from folders and sub folders into a root folder

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.

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)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM