[英]A function to copy folder along with its contents python
Hi is there a function that copies a parent folder along with all its content to a specified destination in python.嗨,是否有一个 function 将父文件夹及其所有内容复制到 python 中的指定目标。
I have used different functions but they seem to copy the contents excluding the parent folder.我使用了不同的功能,但它们似乎复制了不包括父文件夹的内容。
Many thanks非常感谢
shutil.copytree
comes to mind immediately, but your issue is that copying directory foo
in bar
doesn't create bar/foo
. shutil.copytree
立即shutil.copytree
在脑海中,但你的问题是在bar
中复制目录foo
不会创建bar/foo
。
My proposal: 我的建议:
import shutil,os
def copytree2(source,dest):
os.mkdir(dest)
dest_dir = os.path.join(dest,os.path.basename(source))
shutil.copytree(source,dest_dir)
copytree
with the new destination, so source folder name level appears under dest
copytree
,因此源文件夹名称级别显示在dest
There's no subtle check about dest directory already exist or whatnot. 关于dest目录已经存在或什么都没有细微的检查。 I'll let you add that if needed (using
os.path.isdir(dest)
for instance) 如果需要,我会让你添加(例如使用
os.path.isdir(dest)
)
Note that functions from shutil
come with a note which encourages users to copy and modify them to better suit their needs. 请注意,
shutil
中的函数附带一个注释,鼓励用户复制和修改它们以更好地满足他们的需要。
import shutil
shutil.copytree(srcDir, dst, symlinks=False, ignore=None)
In python 3.* we can use shutil
在 python 3.* 我们可以使用
shutil
import shutil
old_folder = "D:/old_folder"
new_folder = "D:/new_folder"
shutil.copytree(old_folder, new_folder, dirs_exist_ok=True)
dirs_exist_ok=True
is for ignoring the exception when the folder already exists in the new location. dirs_exist_ok=True
用于在文件夹已存在于新位置时忽略异常。
Simply append the source directory you want to copy in the destination:只需 append 将要复制到目标的源目录:
import shutil
shutil.copytree("source", "destination/source")
If you do not have fixed strings then use os.path.basename() to determine basename and combine it in the destination with os.path.join()如果您没有固定字符串,则使用 os.path.basename() 来确定 basename 并将其与 os.path.join() 组合到目标中
import os.path
import shutil
source = "/Projekte/python/source"
shutil.copytree(source, os.path.join("destination", os.path.basename(source)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.