python - 备份文件脚本

标签 python backup

我正在编写一个脚本来将文件从一个目录(Master)备份到另一个目录(Clone)。 并且脚本会监控这两个目录。

如果克隆中的文件丢失,那么脚本会将丢失的文件从 Master 复制到 克隆。现在我在创建丢失的文件夹时遇到问题。

我已阅读文档并发现 shutil.copyfile 将创建一个目录,如果 目录不存在。但是我收到一条 IOError 消息,显示目标目录 不存在。下面是代码。

import os,shutil,hashlib
master="C:\Users\Will Yan\Desktop\Master"
client="D:\Clone"

if(os.path.exists(client)):
    print "PATH EXISTS"  
else:
    print "PATH Doesn't exists copying"
    shutil.copytree(master,client)
def walkLocation(location,option):
    aList = []
    for(path,dirs,files) in os.walk(location):
        for i in files:
            if option == "path":
                aList.append(path+"/"+i)
            else:
                aList.append(i)
    return aList

def getPaths(location):
    paths=[]
    files=[]
    result =[]
    paths = walkLocation(location,'path')
    files = walkLocation(location,'files')
    result.append(paths)
    result.append(files)
    return result
ma=walkLocation(master,"path")
cl=walkLocation(client,"path")
maf=walkLocation(master,"a")
clf=walkLocation(client,"a")
for i in range(len(ma)):
    count = 0
    for j in range(len(cl)):
       if maf[i]==clf[j]:
           break
       else:
           count= count+1
    if count==len(cl):
        dirStep1=ma[i][ma[i].find("Master")::]
        dirStep2=dirStep1.replace("Master",client)
        shutil.copyfile(ma[i],dirStep2)

谁能告诉我哪里做错了? 谢谢

最佳答案

抱歉,文档中没有这么说。这是 full documentation for the function 的复制品:

shutil.copyfile(src, dst)

Copy the contents (no metadata) of the file named src to a file named dst. dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. If src and dst are the same files, Error is raised. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.

所以你必须自己创建目录。

关于python - 备份文件脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5604956/

相关文章:

python - 如何向生成器重新抛出异常

python - 没有 shell 提示消息,只是在将 Python 脚本作为守护进程启动后出现闪烁的光标?

内存中的python gzip文件并上传到s3

security - 备份至云端

iphone - 防止备份到 iCloud,以下代码是否正确?

sql-server - SQL Server 更改跟踪、复制、差异备份

python - 试图将大量数据输入 mysqldb

Python scraper如何添加mysql插入

iOS 数据存储问题 - 即使在 NSURLIsExcludedFromBackupKey 之后也被拒绝

svn recovery - 恢复个别修订