在Python中将子文件夹内容移动到父文件夹

9 投票
5 回答
17129 浏览
提问于 2025-04-17 07:58

我在使用Python的时候遇到了一个具体的问题。下面是我的文件夹结构。

dstfolder/slave1/slave

我想把'slave'文件夹里的内容移动到'slave1'(也就是它的上级文件夹)里。移动完成后,'slave'文件夹应该被删除。可是,shutil.move好像没有帮上忙。

请告诉我该怎么做?

5 个回答

0

这个问题可能出在你在shutil.move函数中指定的路径上。

试试这个代码:

import os
import shutil
for r,d,f in os.walk("slave1"):
    for files in f:
        filepath = os.path.join(os.getcwd(),"slave1","slave", files)
        destpath = os.path.join(os.getcwd(),"slave1")
        shutil.copy(filepath,destpath)

shutil.rmtree(os.path.join(os.getcwd(),"slave1","slave"))

把它粘贴到一个.py文件里,放在目标文件夹里。也就是说,slave1和这个文件应该放在一起,然后运行它。这样对我有效。

3

我需要一个更通用的解决方案,也就是说,把所有子文件夹里的文件都移动到根文件夹里。

比如,开始时是这样的:

root_folder
|----test1.txt
|----1
     |----test2.txt
     |----2
          |----test3.txt

最后变成这样:

root_folder
|----test1.txt
|----test2.txt
|----test3.txt

用一个简单的递归函数就能解决这个问题:

import os, shutil, sys 

def move_to_root_folder(root_path, cur_path):
    for filename in os.listdir(cur_path):
        if os.path.isfile(os.path.join(cur_path, filename)):
            shutil.move(os.path.join(cur_path, filename), os.path.join(root_path, filename))
        elif os.path.isdir(os.path.join(cur_path, filename)):
            move_to_root_folder(root_path, os.path.join(cur_path, filename))
        else:
            sys.exit("Should never reach here.")
    # remove empty folders
    if cur_path != root_path:
        os.rmdir(cur_path)

通常你会用相同的参数来调用这个函数,root_pathcur_path,比如如果你想在 Python 环境中试试,可以这样调用:move_to_root_folder(os.getcwd(),os.getcwd())

13

下面是一个使用os和shutil模块的例子:

from os.path import join
from os import listdir, rmdir
from shutil import move

root = 'dstfolder/slave1'
for filename in listdir(join(root, 'slave')):
    move(join(root, 'slave', filename), join(root, filename))
rmdir(join(root, 'slave'))

撰写回答