【发布时间】:2016-02-22 02:22:30
【问题描述】:
我正在尝试创建一个 shell 脚本,它将文件从一台计算机(员工的旧计算机)复制到另一台计算机(员工的新计算机)。感谢这里可爱的人,我已经可以复制文件了,但我遇到了一个问题 - 如果我要从这个有 2 个文件的目录出发:
C:\Users\specificuser\Documents\Test 文件夹 ....到这个目录... C:\用户\特定用户\桌面 ...我看到文件显示在桌面上,但没有创建这些文件所在的文件夹(测试文件夹)。
这是我正在使用的复制功能:
#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 文件夹指定为目标,因此永远不会创建测试文件夹。
-
抱歉,我没看到。所以问题是副本不能递归工作?
-
@PaulK.I 编辑了我的原始帖子,但真正的问题是我希望它比我开始的地方更上一层楼。如果我将 Documents\Test 文件夹中的所有内容移至桌面,我希望它也创建 Desktop\Test 文件夹,即使从技术上讲我没有将目标指定为 Desktop\Test 文件夹,但我指定了桌面。