python實現檔案夾同步

來源:互聯網
上載者:User
定義SynDirTool類,用於同步兩個檔案夾的內容,從/usr/local/a檔案夾到/usr/local/b檔案夾,執行方法:

Python代碼

python SynDirTool.py /usr/local/a  /usr/local/b

SynDirTool.py檔案內容:

Python代碼

#!/usr/bin/python  # -*- coding:utf-8 -*-    import os  import shutil  import sys  import logging  class SynDirTool:      def __init__(self,fromdir,todir):          self.fromdir = fromdir          self.todir = todir        def synDir(self):          return self.__copyDir(self.fromdir,self.todir)        def __copyDir(self,fromdir,todir):          #防止該目錄不存在,建立目錄          self.__mkdir(todir)          count = 0          for filename in os.listdir(fromdir):              if filename.startswith('.'):                  continue              fromfile = fromdir + os.sep + filename              tofile = todir + os.sep + filename              if os.path.isdir(fromfile):                  count += self.__copyDir(fromfile,tofile)              else:                  count += self.__copyFile(fromfile,tofile)          return count        def __copyFile(self,fromfile,tofile):          if not os.path.exists(tofile) :              shutil.copy2(fromfile,tofile)              logging.info("新增%s ==> %s" % (fromfile,tofile))              return 1          fromstat = os.stat(fromfile)          tostat = os.stat(tofile)          if fromstat.st_ctime > tostat.st_ctime:              shutil.copy2(fromfile,tofile)              logging.info("更新%s ==> %s" % (fromfile,tofile))              return 1          return 0          def __mkdir(self,path):          # 去除首位空格          path=path.strip()          # 去除尾部 \ 符號 或者 /          path=path.rstrip(os.sep)            # 判斷路徑是否存在          isExists=os.path.exists(path)            # 判斷結果          if not isExists:              # 如果不存在則建立目錄              logging.info(path+' 目錄建立成功')              # 建立目錄操作函數              os.makedirs(path)  if __name__ == '__main__':      srcdir=sys.argv[1]      descdir=sys.argv[2]      logging.basicConfig(filename='SynDirTool.log', level=logging.INFO)      tool = SynDirTool(srcdir,descdir)      count += tool.synDir()

註:

1,日誌會輸出到SynDirTool.py檔案的相同目錄的SynDirTool.log檔案中

2,如果目的檔案夾已有該檔案,且該檔案較新,則不再會複製源檔案夾中的檔案

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.