我正在尝试创建一个 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 的一部分。这有意义吗?
请您参考如下方法:
您可能想看看 shutil.copytree() .它执行递归复制功能,包括您正在寻找的目录。因此,对于基本的递归复制,您可以运行:
shutil.copytree(srcpath, dstpath)
然而,为了实现将源目录复制到目标目录的目标,在此过程中在目标目录内创建源目录,您可以使用如下内容:
import os
import shutil
def dir_copy(srcpath, dstdir):
dirname = os.path.basename(srcpath)
dstpath = os.path.join(dstdir, dirname)
shutil.copytree(srcpath, dstpath)
请注意,您的 srcpath 末尾不得包含斜杠,否则此功能无法正常工作。另外,目标目录和源目录名的拼接结果必须不存在,否则copytree会失败。
