将子文件夹内容移动到python中的父文件夹

时间:2011-12-08 09:43:29

标签: python

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

dstfolder / SLAVE1 /从

我想将'slave'文件夹的内容移动到“slave1”(父文件夹)。一旦感动, 应删除'slave'文件夹。 shutil.move似乎没有帮助。

请告诉我怎么做?

4 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:2)

我需要一些更通用的东西,即将所有[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)

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

答案 2 :(得分: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"))

将其粘贴到dstfolder中的.py文件中。即slave1和此文件应保持并排。然后运行它。为我工作

答案 3 :(得分:-2)

也许你可以进入字典奴隶,然后

exec system('mv .........')

它会起作用吗?

相关问题