はじめに
Qiita初投稿。いつもお世話になっていたので、そろそろ自分も出来上がったものを公開していこうかと。
各フォルダに散らばっている特定のファイルを一か所に集めたい
こういう事、よく起きませんか?
全てのFolderは同じフォルダ構造を持っていて、sub-sub-folderに眠っているファイル(今回はmdbファイルとしました)をどこか一か所に集めたい..
Codeの実行
毎回忘れては調べるので以下に残します。
環境はJupyter notebookで実行しました。
mdb_collect.py
import os
import shutil
import pandas as pd
# 保存したいディレクトリを指定
file_to = r"the location where you want to save them"
# これから探しだすフォルダ構造のトップを指定
k = os.path.exists(r"Parent folder where you seek the files")
if k==True: #一応、folderが存在するか確認します。
root = r"the location where you seek the files"
for folder, subfolders, files in os.walk(root):
# "sub-sub-folder-1" という名前のfolderを見つけたら
# mdbファイルを探しだし取得する。
if "\sub-sub-folder-1" in folder:
for file in files:
if ".mdb" in file:
file_from = folder + "\\" + file
print(file_from)
shutil.copyfile(file_from,file_to+"\\"+file)
os.walk()がParent Folder以下の階層すべてを歩きわたってくれるんですね。便利。