利用python備份檔案夾

2022-08-29 18:27:09 字數 2335 閱讀 5927

以前寫過乙個非常白痴的備份指令碼,就是將著整個我資料夾都拷貝到u盤裡,每次拷貝前都將已經存在的資料夾刪除掉。這樣的話程式就很傻瓜**也很少

1

importos2

3def

backup(from_path,to_path):4if

os.path.exists(to_path):

5 os.system('

rm -rf to_path')

6 os.system('

cp from_path to_path

')

今天在python cookbook上看到一段**,這段**也是利用python進行備份檔案夾,但是它的程式要聰明一點,只拷貝那些還未被備份的檔案

1

import

os,sys,shutil,filecmp23

#def backup(path,backdirname = 'back'):4#

for dir,subdir,files in os.walk(path):5#

if backdirname not in subdir:6#

backdir = os.path.join(dir,backdirname)7#

os.mkdir(backdir)8#

subdir[:] = [d for d in subdir if d !=backname]9#

for file in files:10#

filepath = os.path.join(dir,file)11#

for index in xrange(100):12#

backfile = '%s.%2.2%d'%(file,index)13#

backpath = os.path.join(dir,backfile)14#

if os.path.exists(backpath):break15#

if index>0:16#

old_backpath

1718

def backup(path,backdir_name='

backdir'):

19 maxversions = 100

20for dir,subdir,files in

os.walk(path):

21 backdir =os.path.join(dir,backdir_name)

22if

notos.path.exists(backdir):

23os.mkdir(backdir)

2425 subdir[:] = [d for d in subdir if d !=backdir_name]

26for file in

files:

27 filepath =os.path.join(dir,file)

28 backpath =os.path.join(backdir,file)

2930

for index in

xrange(maxversions):

31 backfile_name = '

%s.%2.2d

'%(backpath,index)

32if

not os.path.exists(backfile_name):break

3334

35if index>0:

36 old_backup = '

%s.%2.2d

'%(backpath,index-1)

37 abspath =os.path.abspath(filepath)

38try:39

if os.path.isfile(abspath) and filecmp.cmp(old_backup,abspath,shallow =false):

40continue

41except

oserror:

42pass

4344

try:

45shutil.copy(filepath,backfile_name)

46except

oserror:

47pass

48if

__name__ == '

__main__':

49 path = raw_input('

please input the backup dir:')

50 backup(path)

mysql備份檔案夾 mysql 備份

mysql定期備份是一項重要的工作,但人工操作太繁瑣,也難避免有所疏漏,使用下面的方法即可讓系統定期備份資料。1 建立備份檔案夾 cd www makedir backup 2 編寫執行指令碼 vi autobackup 寫入以下內容 filename date y m d mysql bin di...

不改變檔案 夾 屬性備份檔案 夾

1.tar 壓縮 root admin test ls all drwxr xr x 2 admin root 4096 jan 21 03 50 test root admin test tar czf test.tar.gz test root admin test ls all drwxr x...

用Matlab來備份檔案夾

由於各種各的原因,我們需要備份一些資料夾,例如過幾天onedrive的容量將減少,不想公升級的使用者必須刪減內容或者備份內容。但是簡單的複製資料夾會造成一些問題,例如導致歷史資料丟失 少量的變動也需要複製所有資料。為了克服這個問題,我用matlab寫了乙個簡單的資料夾備份程式,實現以下功能 如果目標...