3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python]各フォルダに散らばっている特定のファイルを一か所に集めたい

Last updated at Posted at 2020-05-19

はじめに

Qiita初投稿。いつもお世話になっていたので、そろそろ自分も出来上がったものを公開していこうかと。

各フォルダに散らばっている特定のファイルを一か所に集めたい

こういう事、よく起きませんか?
全てのFolderは同じフォルダ構造を持っていて、sub-sub-folderに眠っているファイル(今回はmdbファイルとしました)をどこか一か所に集めたい..

image.png

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以下の階層すべてを歩きわたってくれるんですね。便利。

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?