フォルダ内のファイルを移動するスクリプトを作成したけど、そうだ、その前にそのフォルダが存在するかどうか?を確認する必要がある。加えてそのフォルダが無かったら作成することも入れておかないと・・・・あ、作成するフォルダも1つではなく、2つある場合は・・・意外とやることあるなぁ。
◆スクリプト(フォルダの存在確認)
# =================================== # Check Target directory exists, or not # If nothong, create Target directory # =================================== # =================================== # import # =================================== import os # =================================== # function # =================================== # Array of Dicretory name def CreateArray(currentdir,nameDir): Target_dir=[] for i in nameDir: Target_dir.append(currentdir + i) return Target_dir # ---------------------------------- # Check Target directory exists def Checkdirexists(dirpath): a = os.path.exists(dirpath) return a # conditinal branch def FlagBoolCheck(checkflag): if checkflag == True: print("Directory exists") else: print("directory noting") return checkflag # Create Target Directory def CreateDir(new_dir_path): os.mkdir(new_dir_path) # End message def MessageDone(): print("Create new directory") # =================================== # ready for exe # =================================== # current directory currentdir = os.getcwd() # Target directory name nameDir = ('/fig','/trash') # for checking, get them into array Target_dir = CreateArray(currentdir,nameDir) # =================================== # execution # =================================== for i in Target_dir: checkflag = Checkdirexists(i) fl = FlagBoolCheck(checkflag) # If Target directory nothing, create it if fl == False: CreateDir(i) MessageDone()
これらのスクリプトはラズパイで定期実行させる予定なので、いまのうちに整理しておかないと。pythonもようやく慣れてきた。関数を作るようになるとタパル?リストの使い方も分かってくる。というか分からないと引数渡しに困ったりするから…。それにしてもpythonの引数渡しはすごいやりやすい感触がある。型とかあまり意識しないでも渡せるので。