Python:递归地将所有文件从文件夹和子文件夹移动到根文件夹

uinbv5nw  于 2022-11-26  发布在  Python
关注(0)|答案(2)|浏览(228)

给定一个包含很多dept的文件树,如下所示:

├── 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

如何将所有项目递归移动到当前工作目录中:

├── movepy.py
│── erwer.txt    
│── sdffg.txt
├── hoihoi.txt
├── hoihej.txt
├── dfsdf.txt
└── dsfsdfsd.txt
  • 这个问题中的文件树是一个例子,在现实中我想移动一个树,有许多嵌套的子文件夹与许多嵌套的文件。*
kxkpmulp

kxkpmulp1#

这应该可以达到你想要达到的目的。

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

ruoxqz4g2#

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)

相关问题