Gohome_soon 发表于 2018-8-1 16:22:43

Python实现备份文件程序

本帖最后由 Gohome_soon 于 2018-8-1 16:22 编辑

学习Python有一段时间了,了解了基本语法,自己尝试写了一个文件备份程序。
这个程序还有许多bug,能力问题,看以后要在优化吧
参考了https://www.cnblogs.com/xiao1/p/6171064.html

update_form(需要备份的源文件)                默认设置成 'E:\\WorkStation\\12-Ubuntu\\scwLinux\\wSation\\'
update_to      (备份文件存储位置)                默认是 'G:\\WorkStation\\12-Ubuntu\\scwLinux\\wSation\\'
这些需要在在实例化时设置:update_t = update(update_form = "...",update_to="...")

原文中使用            import re
                        destination_dir = re.sub(dir1,dir2,item)
来替换需要备份的文件夹路径,而我在调用中出现错误,没有能力解决,所以我固定使用 destination_dir = item.replace("E:\\","G:\\") ,这点需要更改的,没有实现自动匹配


#coding:utf-8
import os
import filecmp
import shutil
import time
class update(object):
      def __init__ (self,update_from = None,update_to = None):
                if update_from is None:
                        self.__update_from = 'E:\\WorkStation\\12-Ubuntu\\scwLinux\\wSation\\'#备份target_dir文件到back_dir
                else:
                        self.__update_from = update_from

                if update_to is None:
                        self.__update_to = 'G:\\WorkStation\\12-Ubuntu\\scwLinux\\wSation\\'#将target_dir文件备份到back_dir
                else:
                        self.__update_to = update_to

                self.holderlist = []

      def __compareme(self,dir1,dir2):    #递归获取更新项函数
                dircomp = filecmp.dircmp(dir1,dir2)
                only_in_one = dircomp.left_only      #只在左边文件夹中存在的文件或文件夹;
                diff_in_one = dircomp.diff_files   #不匹配文件,源目录文件已发生变化
                dirpath = os.path.abspath(dir1)      #定义源目录绝对路径

                #只在左边存在的文件中如果是文件夹,则创建
                for item in only_in_one :
                        #判断只有左边有的文件是文件夹或者其他
                        item_file=os.path.abspath(os.path.join(dir1,item))
                        if os.path.isdir(item_file): #如果是文件夹
                              item_t=os.path.abspath(os.path.join(dir2,item))                                 
                              if not os.path.exists(item_t):#在右边创建改文件夹
                                        os.makedirs(item_t)
                                        dircomp.common_dirs.append(item)#加入共同拥有的列表中,便于下面递归调用
                        else:
                              self.holderlist.append(item_file)#如果是文件,则将改文件路径添加入holderlist中
                #将更新文件或目录追加到holderlist
                [ self.holderlist.append(os.path.abspath(os.path.join(dir1,x))) for x in diff_in_one ]
                if len(dircomp.common_dirs) > 0:#判断是否存在相同子目录,以便递归
                        for item in dircomp.common_dirs:   #递归子目录
                              self.__compareme(os.path.abspath(os.path.join(dir1,item)),os.path.abspath(os.path.join(dir2,item)))
                return self.holderlist

      def messagStr (self,dirstr):
                outDirStr = ''
                if len(dirstr) < 30:
                        outDirStr = dirstr
                else:
                        outDirStr = '...'
                        endNum = len(dirstr)
                        startNum = endNum-30

                        while True:
                              if not dirstr == '\\':
                                        if startNum < endNum:
                                                startNum = startNum+1
                                        else:
                                                startNum = 30
                                                break
                              else:
                                        break

                        outDirStr += dirstr
                return outDirStr

               
      def update(self):
                destination_files=[]
                source_files = self.__compareme(self.__update_from,self.__update_to)    #对比源目录与备份目录
                self.__update_from = os.path.abspath(self.__update_from)    #取绝对路径后,后面不会自动加上'/'
                self.__update_to = os.path.abspath(self.__update_to)
                for item in source_files:   #遍历返回的差异文件或目录清单
                        destination_dir = item.replace("E:\\","G:\\")
                        destination_files.append(destination_dir)
               
                copy_pair = zip(source_files,destination_files)#将源目录与备份目录文件清单拆分成元组
                num=0
                if len(source_files)>0:
                        print('update :')
                        for item in copy_pair:
                              if os.path.isfile(item):      #判断是否为文件,是则进行复制操作
                                        outStr = self.messagStr(item)
                                        print('\t%s update:\t%s'%(time.strftime("%H-%M-%S"),outStr))   #输出更新项列表清单
                                        num += 1
                                        shutil.copyfile(item,item)
                else:
                        print('nothing to update !')
if __name__ == "__main__":
      update_t = update()
      update_t.update()


不再犹豫 发表于 2018-8-1 18:37:06

楼主有什么比较好的入门的学习资料吗 我也想学学{:handshake:}

apeng2012 发表于 2018-8-1 19:17:22

destination_dir = re.sub(r":", "G:", item)

Gohome_soon 发表于 2018-8-1 20:23:27

apeng2012 发表于 2018-8-1 19:17
destination_dir = re.sub(r":", "G:", item)

{:shy:}能详细说明下吗,有点看不懂

Gohome_soon 发表于 2018-8-1 20:24:17

不再犹豫 发表于 2018-8-1 18:37
楼主有什么比较好的入门的学习资料吗 我也想学学

网上找的资料,也没专门看什么说,了解了一些基本语法,不深入

xy-mcu 发表于 2018-8-1 21:14:18

www.liaoxufeng.com

duxingkei 发表于 2018-8-1 22:49:27

这种好像linux一条 sync命令就搞定了
win下 就不知道了
页: [1]
查看完整版本: Python实现备份文件程序