2023年4月10日 星期一

檔案備份v2

import os
import shutil
from datetime import datetime
this_day=datetime.now()
k11_year=str(this_day.year-1911)+'年'
k11_month=str(this_day.month)+'月'
k11_day=this_day.strftime('%m%d')

k11_path_check=f'C:\\Users\\K\\OneDrive\\桌面\\公園\\晨運\\02_每日紀載'
'''檔案txt路徑'''
k11_path=os.path.join(k11_path_check,k11_year,k11_month,k11_day)
print(os.listdir(k11_path_check))
print(os.path.exists(k11_path))

'''確認k11_path'''
if os.path.exists(k11_path) == False:
    '''路徑不存在就建立'''
    # os.mkdir(k11_path)
    os.makedirs(k11_path)
print(os.listdir(k11_path_check))
'''
一開始使用os.mkdir()不斷失敗,他只能創建單個目錄,且父目錄必須存在
跳出FileNotFoundError: [WinError 3] 系統找不到指定的路徑。:
直到我使用
os.makedirs(),他可以創建多層目錄,並且當父目錄不存在時,會自動創建父目錄
'''

'''確認backup_path'''
backup_year=str(this_day.year-1911)+'年度'
backup_month=str(this_day.year-1911)+this_day.strftime('%m')
backup_day=this_day.strftime('%m%d')
backup_path_check='C:\\Users\\K\\OneDrive\\桌面\\bakcup\\安安'
'''備份txt路徑'''
backup_path=os.path.join(backup_path_check,backup_year,backup_month,backup_day)

if not os.path.exists(backup_path):
    '''路徑不存在就建立'''
    os.makedirs(backup_path)



print('目前今日的檔案',os.listdir(k11_path))
print('目前備份區的檔案',os.listdir(backup_path))

'''使用filecmp的dircmp()檢查目錄下的檔案是否相同'''
import filecmp
comp=filecmp.dircmp(k11_path,backup_path)

if comp.left_only != None:
    print('備份中')
    for file in comp.left_only:
        shutil.copy2(os.path.join(k11_path,file),backup_path)
    print('備份完畢')
    print('備份區檔案:',os.listdir(backup_path))

---------------------------------------------------------------------------------


#根據檔案備份 所寫的程式庫



import os
import shutil
from datetime import datetime

class file_time(datetime):
    def chinese_year(t):
        return str(t.year-1911)
    def mon(t):
        return str(t.month)
    def m_d(t):
        return t.strftime("%m%d")
    def m(t):
        return t.strftime("%m")

class file_path():
    def path_plus(path1,*path2):
        "使用os.path.join加入路徑"
        return os.path.join(path1,*path2)
   
    def path_check(path):
        "檢查路徑是否存在"
        return os.path.exists(path)
   
    def look_path_file(path):
        "查看路徑底下的檔案"
        return os.listdir(path)
    def make_path(path):
        "創造路徑"
        return os.makedirs(path)
   
    def comp_path_(path1,path2):
        import filecmp
        comp=filecmp.dircmp(path1,path2)
        "將檔案比對結果存放在comp"
        return comp
    def copy_file(path1,path2):
        "複製檔案A到B"
        return shutil.copy2(path1,path2)
















0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁