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

2024-04-19 13:32:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个特殊的问题。下面是我的文件夹结构。

dstfolder/slave1/从机

我想把“slave”文件夹的内容移到“slave1”(父文件夹)。一旦移动, 应删除“从属”文件夹。舒蒂尔,搬家似乎没用。

请告诉我怎么做?


Tags: 文件夹内容结构slaveslave1dstfolder
3条回答

问题可能出在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"))

将其粘贴到dstfolder中的.py文件中。一、 slave1和这个文件应该并排保存。然后运行它。为我工作

我需要一些更通用的东西,即将所有文件从所有[sub]+文件夹移到根文件夹中。

例如,开始于:

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)

如果您想在python环境中尝试,通常会用相同的参数来调用它,例如root_pathcur_path,例如move_to_root_folder(os.getcwd(),os.getcwd())

使用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(root)

相关问题 更多 >