繁体   English   中英

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

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

给定一个包含很多部门的文件树:

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

这个问题中的文件树就是一个例子,实际上我想移动一棵树,它有许多嵌套的子文件夹和许多嵌套的文件。

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)

这应该可以解决您要实现的目标。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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