我试图创建一个shell脚本,将文件从一台计算机(员工的旧计算机)复制到另一台(员工的新计算机)。我已经到了可以复制文件的地步,这要感谢可爱的人在这里,但是我遇到了一个问题 - 如果我从这个目录有两个文件:Python:复制文件时创建文件夹
C :\ Users \ specificuser \ Documents \测试文件夹 ....到这个目录... C:\ Users \ specificuser \ Desktop ...我看到文件显示在桌面上,但文件夹这些文件是(测试文件夹)中未创建。
这里是我使用的复制功能:
#copy function
def dir_copy(srcpath, dstpath):
#if the destination path doesn't exist, create it
if not os.path.exists(dstpath):
os.makedir(dstpath)
#tag each file to the source path to create the file path
for file in os.listdir(srcpath):
srcfile = os.path.join(srcpath, file)
dstfile = os.path.join(dstpath, file)
#if the source file path is a directory, copy the directory
if os.path.isdir(srcfile):
dir_copy(srcfile, dstfile)
else: #if the source file path is just a file, copy the file
shutil.copyfile(srcfile, dstfile)
我知道我需要在目的地创建目录,我只是不太清楚如何去做。
编辑:我发现我有一个类型(os.makedir而不是os.mkdir)。我测试了它,它创建了它应该的目录。但是我希望它能从创建目录的一层开始创建目录。例如,在测试文件夹中有子测试文件夹。它创建了子测试文件夹,但不会创建测试文件夹,因为测试文件夹不是dstpath的一部分。那有意义吗?
@PaulK。我已经把它作为函数的第一件事了。但是,我认为问题在于我的“目标”是桌面 - 我没有将Desktop \ Test Folder指定为目标,所以测试文件夹永远不会被创建。 –
我道歉,我没有看到。所以问题是该副本不能递归地工作? –
@ PaulK.I编辑了我原来的帖子,但真正的问题是,我希望它从我开始的地方上升一级。如果我将Documents \ Test文件夹中的所有内容都移动到桌面,我希望它也创建Desktop \ Test文件夹,即使技术上我没有将目标指定为Desktop \ Test Folder,但我指定了Desktop。 –