-1

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

谢谢大家的帮助!

编辑:如果它可以兼容 python 2.5,那就太好了。

4

1 回答 1

2

这是一个准系统代码,如果它们在目录中具有相同的结构,它将同步两个目录。

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或 hashes(如下)以检查您之前是否复制过该文件。

import hashlib
def cmpHash(file1,file2):
    """ Compares two files' hashes to determine duplicates. This doesn't work out so well, possibly due to different metadata"""
    hash1 = open(file1,'r').read()
    hash2 = open(file2,'r').read()
    #returns true if the files are the same - otherwise, false.
    return  hashlib.sha512(file1).hexdigest() == hashlib.sha512(file2).hexdigest()

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

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
于 2013-08-01T14:06:04.523 回答