最終更新から一定時間経過したファイルを移動する(Pythonで自動化)

最近はPythonの勉強をしています。一方でFXのEAを作って動かしています。FXのEAを動かすMetaTraderは、ログファイル等が原因でとあるディレクトリ内のデータサイズが一定サイズ以上になるとEAが動かなくなるので、定期的にログファイルを退避させるようにしてます。

簡単に言うと、ログファイルが増えすぎるとプログラムが止まるので自動退避させるスクリプトをPythonで作りたい、ということになります。

やりたいこと

ざっくりとこんなことがしたいです

  1. WindowsのタスクスケジューラでPythonスクリプトを実行
  2. Pythonスクリプトでは予め用意したCSVファイルを取り込む
  3. CSVファイルに記載されたディレクトリ、条件等からファイルを移動する

このうち、2,3あたりをPythonで作成する必要があります。

Pythonのアルゴリズム案

アルゴリズムのブレインストーミングです。Python初心者なのでうまくいくか分かりませんが、以下のアルゴリズムを想定して作成していきます。

  • モジュールのインポート
  • CSVファイルのパスを定義
  • CSVの取り込み
  • 1行目を取得
    • 値が空なら自作Errorを出してスクリプトを終了する。
  • N行目を取得
    • EnableがFalseなら次の行にいく
    • Targetディレクトリが存在しなければ自作Errorを出して次の行にいく
    • 対象ファイルの更新日時を調べ、DaysOldが値(例では3日)以上でなければ次の行に行く
    • Destinationのディレクトリが存在しなければ作成する
    • 対象ファイルを移動する
    • 次の行に行く

使用するCSV

今回使用するCSVファイルのカラムです。

完成したスクリプト

私にとって初めてのPythonスクリプトなので、「きれいにできているか」といったらそうではないかも知れません。でも、動きます。

Pythonは誰が書いてもおおよそ読みやすくなると言いますが、実際に書いてみてそう思いました。「ここで改行すべきかな、しておこうかな」という考えはほぼありませんでした。

# 00. For Debugging - Development Purpose
def myDebug(argMsg=""):
    print(f"myDebug, {argMsg}")

# 10. Import modules
import csv
import os
import time
import shutil as sh

# 15. Functions
def Return_LastModified_TimeCounts(argFile=None, argPeriod=None):

    import os

    if argFile is None:
        return
    if argPeriod is None:
        return

    LastModified_Seconds = int(os.path.getmtime(argFile))
    LastModified_Minutes = int(LastModified_Seconds / 60)
    LastModified_Hours = int(LastModified_Minutes / 60)
    LastModified_Days = int(LastModified_Hours / 24)
    LastModified_Weeks = int(LastModified_Days / 7)

    if argPeriod == "Seconds": return(LastModified_Seconds)
    if argPeriod == "Minutes": return(LastModified_Minutes)
    if argPeriod == "Hours": return(LastModified_Hours)
    if argPeriod == "Days": return(LastModified_Days)
    if argPeriod == "Weeks": return(LastModified_Weeks)

    return()

def Return_Current_TimeCounts(argPeriod=None):
    import time
    if argPeriod is None:
        return

    Current_Seconds = int(time.time())
    Current_Minutes = int(Current_Seconds / 60)
    Current_Hours = int(Current_Minutes / 60)
    Current_Days = int(Current_Hours / 24)
    Current_Weeks = int(Current_Days / 7)

    if argPeriod == "Seconds": return(Current_Seconds)
    if argPeriod == "Minutes": return(Current_Minutes)
    if argPeriod == "Hours": return(Current_Hours)
    if argPeriod == "Days": return(Current_Days)
    if argPeriod == "Weeks": return(Current_Weeks)
    return()

# 20. Define parameters
Param_File = r"C:\Users\Administrator\abbr\Parameters.csv"
CSV_No = 0
CSV_Enable = 1
CSV_Target = 2
CSV_DaysOld = 3
CSV_Destination = 4


# 30. Read CSV
with open(Param_File) as Param:
    reader = csv.reader(Param)
    for row in reader:

    # 40. Get row
	    # 40-1. Continue if A1 row is empty
        if row[CSV_No] == "":
            continue

        # 40-2. Skip 1st row (where row[0] is "No")
        if row[CSV_No] == "No":
            continue

        # 50. Get rows with parameters
        if row[CSV_No] != "":

            # 50-1 Skip if "Enable" is False
            if row[CSV_Enable] == "False":
                continue

            # 50-2 Continue if target directory does not exist
            if os.path.exists(row[CSV_Target]) == False:
                continue

            # 50-3 Get file info
            for file in os.listdir(row[CSV_Target]):

                # 50-3-1 Get file info and compare with condition
                FileFullPath = os.path.join(row[CSV_Target], file)
                tempLasModi = Return_LastModified_TimeCounts(FileFullPath, argPeriod="Days")
                tempCurTime = Return_Current_TimeCounts("Days")
                tempDiff = tempCurTime - tempLasModi
                if tempDiff < int(row[CSV_DaysOld]):
                    continue

                # 50-4 Make destination directory if it doesn't exit
                if os.path.exists(row[CSV_Destination]) == False:
                    os.makedirs(row[CSV_Destination], exist_ok=True)

                # 50-5 Move target file
                NewPath = sh.move(FileFullPath, row[CSV_Destination])
よっさん
  • よっさん
  • 当サイトの管理人。ニューヨークの大学を飛び級で卒業。その後某日系IT企業でグローバル案件に携わる。マレーシアに1.5年赴任した経験を持つ。バイリンガルITエンジニアとしていかに楽に稼ぐか日々考えている。

コメントする

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