python實現檔案夾同步

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

Python代碼

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

SynDirTool.py檔案內容:

#!/usr/bin/python# -*- coding:utf-8 -*-import osimport shutilimport sysimport loggingclass SynDirTool:def __init__(self,fromdir,todir):self.fromdir = fromdirself.todir = todirdef synDir(self):return self.__copyDir(self.fromdir,self.todir)def __copyDir(self,fromdir,todir):#防止該目錄不存在,建立目錄self.__mkdir(todir)count = 0for filename in os.listdir(fromdir):if filename.startswith('.'):continuefromfile = fromdir + os.sep + filenametofile = todir + os.sep + filenameif os.path.isdir(fromfile):count += self.__copyDir(fromfile,tofile)else:count += self.__copyFile(fromfile,tofile)return countdef __copyFile(self,fromfile,tofile):if not os.path.exists(tofile) :shutil.copy2(fromfile,tofile)logging.info("新增%s ==> %s" % (fromfile,tofile))return 1fromstat = 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 1return 0def __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()
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.