【问题标题】:Backup File Script备份文件脚本
【发布时间】:2014-07-26 23:06:20
【问题描述】:

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

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

我已经阅读了文档,发现 shutil.copyfile 会创建一个目录,如果 dir 不存在。但我收到一条 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)

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

【问题讨论】:

  • 使用 rsync 或 robocopy 会不会更容易

标签: python backup


【解决方案1】:

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

shutil.copyfile(src, dst)

复制 文件的内容(无元数据) 命名为src 到一个名为dst 的文件。 dst 必须是完整的目标文件名; 查看copy() 以获取接受的副本 目标目录路径。如果src 和 dst 是同一个文件,Error 是 提高。目的地位置必须 可写;否则,IOError 将引发异常。如果dst 已经存在,将被替换。 特殊文件,例如字符或 块设备和管道不能 使用此功能复制。 src 和 dst 是以字符串形式给出的路径名。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    相关资源
    最近更新 更多