如何编写一个python脚本来复制文件而不复制已有的文件?

2024-09-29 17:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个业余爱好者,请耐心等待。所以这就是我需要的。我需要把文件从一个文件夹移到另一个文件夹。在目标文件夹中,新文件将被手动排序。这个脚本将通过一个windows服务pycron每五分钟运行一次。我需要知道如何编写这个脚本,这样它就不会复制已有的东西。我需要创建一个额外的文件来跟踪它吗?在

谢谢大家的帮助!在

编辑:如果它可以兼容Python2.5,那就太好了。在


Tags: 文件脚本文件夹编辑目标排序windows手动
1条回答
网友
1楼 · 发布于 2024-09-29 17:24:09

下面是一个基本代码,如果两个目录在目录中具有相同的结构,那么它们将同步化。在

import shutil
import os
#Assuming your folders are identical for synchronization purposes
root_src_dir = "Path\To\Source"
root_dst_dir = "Path\To\Dest"
for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir)
    if not os.path.exists(dst_dir):
        os.mkdir(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        #dst_file = os.path.join(dst_dir, file_)
        #Decides whether or not to replace files in the destination
        if os.path.exists(os.path.join(root_dst_dir,dst_file)): #EDIT HERE.
            continue
        else:
            print "Copying", dst_file
            shutil.copy(src_file,os.path.join(root_dst_dir,dst_file)) #EDIT HERE

这将自动创建源目录到目标目录的“副本”。它将创建丢失的子目录,并将这些特定位置的文件复制到目标目录,前提是目标目录中还不存在该文件。在

如果你想确定文件是否相同,那么你可能需要查看filecmp或哈希(如下)来检查你之前是否复制过该文件。在

^{pr2}$

示例:(编辑后不再为真)。在

DriveA:\SomeDirectory\SourceDirectory\-Stuff-
DriveB:\DestDirectory\-Stuff-
#All -Stuff- from the SourceDirectory will be copied to DestDirectory, regardless of directories infront of Source/Dest Directory

相关问题 更多 >

    热门问题