ファイルを名前に日時付与してバックアップする|Python自動化

CSVで対象のファイルを指定し、そのファイル名に日時情報を付与した上で、CSV指定したディレクトリにバックアップするスクリプトです。

例えば、「work\MyFile.txt」を「backup\」ディレクトリに「MyFile_20211225-0923」という名前にしてコピーします。私の場合は共有フォルダにある共有されたファイルだけど、個人的にバックアップ(バージョン管理ぽいこと)をしたい場合に使います。

やりたいこと

簡単な流れです。

  • タスクスケジューラでスクリプトを実行
  • スクリプトからCSVファイルを読み込む
  • 対象のファイルを取得する
  • 新しいファイル名(日時情報付与)を組み立てる
  • 宛先のディレクトリにコピーする

使用するCSV

今回使用するCSVのカラムです。

コード

コードです。まだPython初心者なので、きれいなコードと言えるかわかりませんが、動きます。また、ログを吐き出す機能も入れてます。

# v1.0: First version


# 10. Import Modules
import csv
import os
import shutil as sh

# 20. Functions
# 20-1. Function for ErrorDebug
def Write_Log(argMsg="No message", argSeverity=3, argTimeType=0, argLogFileDirectory=None):
    import os
    import datetime as dt

    # Parameter
    DefaultLogFileDirectory = os.getcwd()
    Severity = {0:"EVERGENCY",
                1:"ALERT",
                2:"CRITICAL",
                3:"ERROR",
                4:"WARNING",
                5:"NOTIFICATION",
                6:"INFOMATION",
                7:"DEBUG"}
    DatePattern = {0:"%Y/%m/%d,%H:%M:%S",
                    1:"%b %d %Y,%H:%M:%S",
                    2:"%Y:%m:%d-%H:%M:%S"}

    # Get time
    NowTime = dt.datetime.now()

    # Create message
    MessageParts = []
    MessageParts += [NowTime.strftime(DatePattern[argTimeType])]
    MessageParts += [Severity[argSeverity]]
    MessageParts += [str(argMsg)]
    Message = ",".join(MessageParts)
    print(Message)

    # Log file name
    LogFileName = NowTime.strftime("%Y%m%d.log")
    if argLogFileDirectory != None:
        LogFilePath = os.path.join(argLogFileDirectory, LogFileName)
    if argLogFileDirectory == None:
        LogFilePath = os.path.join(DefaultLogFileDirectory, LogFileName)

    # Append the message to the log file
    with open(LogFilePath, "a") as LogFile:
        LogFile.write(Message+"\n")

# 20-2. Function for returning date with specified format
def Return_Formated_Date(argType=0):
    import datetime as dt
    Format = {0:"%Y%m%d-%H%M%S",
                1:"%b %d %Y,%H:%M:%S",
                2:"%Y:%m:%d-%H:%M:%S",
                3:"%Y/%m/%d,%H:%M:%S"}
    # Get time & Format it
    NowTime = dt.datetime.now()
    Formated = NowTime.strftime(Format[argType])
    Formated = str(Formated)
    return(Formated)

Write_Log("Starts.", 6, 0)

# 30. Define parameters
ParameterFile = r"C:\Users\Administrator\abbr\Parameters.csv"
CSV_No = 0
CSV_Enable = 1
CSV_Target = 2
CSV_Destination = 3

# 40. Read CSV
with open(ParameterFile) as param:
    reader = csv.reader(param)

    for row in reader:
        # 40-1. break if 1:1 is empty
        if row[CSV_No] == "":
            break
    	# 40-2. continue if 1:1 is "No" to go to the next row
        if row[CSV_No] == "No":
            continue
        # 40-3. break if 2:1 is empty
        if row[CSV_No] == "":
            Write_Log("Detect 1st column is empty", 3, 0)
            break
	    # 50. EnableがFalseならcontinue
        if row[CSV_Enable] == False:
            Write_Log("Enable status is false, {row[CSV_Target]}", 6, 0)
            continue
	    # 50-1. continue if Target does not exist
        if os.path.exists(row[CSV_Target]) == False:
            Write_Log(f"No target file, {row[CSV_Target]}", 3, 0)
            continue
	    # 50-2. Create destination directory if not exist
        if os.path.exists(row[CSV_Destination]) == False:
            Write_Log("Create destination directory", 6, 0)
            os.makedirs(row[CSV_Destination], exist_ok=True)
            if os.path.exists(row[CSV_Destination]) == True:
                Write_Log(f"Directory created, {row[CSV_Destination]}")
	    # 60. Get formated date for new file name
        BackupTime = Return_Formated_Date()
        # 60-1. Make new file name
        NewName = os.path.splitext(os.path.basename(row[CSV_Target]))[0]
        temp_Extension = os.path.splitext(os.path.basename(row[CSV_Target]))
        temp_Position = len(temp_Extension) - 1
        Extension = temp_Extension[temp_Position]
        NewName = NewName + "_" + BackupTime + Extension
        Write_Log(f"NewName is {NewName}", 7,0)
        NewFileFullPath = os.path.join(row[CSV_Destination], NewName)
        # 60-2. Copy file
        sh.copy2(row[CSV_Target], NewFileFullPath)

よっさん
  • よっさん
  • 当サイトの管理人。ニューヨークの大学を飛び級で卒業。その後某日系IT企業でグローバル案件に携わる。マレーシアに1.5年赴任した経験を持つ。バイリンガルITエンジニアとしていかに楽に稼ぐか日々考えている。

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です