我在python中遇到了特定的问题。以下是我的文件夹结构。在python中将子文件夹内容移动到父文件夹中
dstfolder/SLAVE1 /从
我想 '从' 文件夹的内容将被移动到 “SLAVE1”(父文件夹)。一旦移动, “奴隶”文件夹应该被删除。 shutil.move似乎没有帮助。
请让我知道该怎么做?
我在python中遇到了特定的问题。以下是我的文件夹结构。在python中将子文件夹内容移动到父文件夹中
dstfolder/SLAVE1 /从
我想 '从' 文件夹的内容将被移动到 “SLAVE1”(父文件夹)。一旦移动, “奴隶”文件夹应该被删除。 shutil.move似乎没有帮助。
请让我知道该怎么做?
例子:
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)
感谢tito,微小的变化和它的工作!抱歉不能投票,因为我的声望很低:-( –
你不能upvote,但你可以验证回应:) – tito
也可以使用, 移动父文件夹内容到一个新的子文件夹让我们说你需要将dir1/*移至dir1/dir2。所以你可以做, 'shutil.move(“dir1”,“dir2)' 'shutil.move(”dir2“,oa.path.join(”dir1“,”dir2“)' –
也许你可以进入字典奴隶,然后
exec system('mv .........')
它将工作不是吗?使用的操作系统和shutil模块
这个答案是特定于POSIX操作系统的,并且会导致代码的便携性降低。 – jhrf
的问题可能与你在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"))
贴吧到dst文件夹中的.py文件中。即slave1和这个文件应该保持并排。然后运行它。为我工作
另外检查你是否有所需的权限也是如此 – Pulimon
我需要一些更通用的东西,即将所有[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_path
和cur_path
的相同说法,例如move_to_root_folder(os.getcwd(),os.getcwd())
如果你想在Python环境中尝试它。
你有什么尝试? 'shutil.move(src,dst)'文档说“递归移动一个文件或目录(src)到另一个位置(dst)”,所以它应该起作用。 – jcollado