LoginSignup
0
1

More than 1 year has passed since last update.

【自動化】ファイルを種類ごとにフォルダーに振り分ける

Last updated at Posted at 2023-02-06

この記事を読んでできるようになること

  • 任意のフォルダーを自動的に作成し、そのフォルダーに自動的にファイルを割り振る

使用例

  • Word, Excelなど様々な形式のファイルが入っているフォルダーがある。それらを、ファイルの形式ごとの新しいフォルダーを作成し(e.g., word)、任意のフォルダーへファイルを振り分ける。
    image.png

コード

モジュールのインポート

import os
import glob
import shutil

作業ディレクトリ内に、フォルダーを作成

フォルダーの名前を指定する際に、そのフォルダーまでのパスを指定することもできます。
例)os.mkdir('C:/Users/tokai/Documents/TokaiOnAir/text')

os.mkdir('word') # os.mkdir('好きな名前を入力')
os.mkdir('text')
os.mkdir('excel')

任意の形式のファイルをすべて取得

globに関する解説記事 【1】

word_files = glob.glob('*.docx')
txt_files = glob.glob('*.txt')
excel_files = glob.glob('*.xlsx')

ファイル数を確認

print('Wordファイルは全部で',{len(word_files)}, 'ファイルあります')
print('txtファイルは全部で',{len(txt_files)}, 'ファイルあります')
print('Excelファイルは全部で',{len(excel_files)}, 'ファイルあります')

出力↓
image.png

ファイルの形式に応じて、指定したフォルダーへ移動させる

3つの形式が入っている変数(「任意の形式のファイルをすべて取得」で作成した変数)を一つにまとめます。
まとめた変数に対し、forとif、そしてshutil.moveを組み合わせて各フォルダーへ、ファイルを振り分けていきます。

wte_files = word_files + txt_files + excel_files #すべてのファイルを一つの変数にまとめる

for file_name in wte_files:
    if file_name in word_files: 
        shutil.move(file_name,'「word」フォルダーへのパス')
    elif file_name in txt_files:
        shutil.move(file_name,'「text」フォルダーへのパス')
    elif file_name in excel_files:
        shutil.move(file_name,'「excel」フォルダーへのパス')

最後に

 今回は、作成したいディレクトリや、取得したいファイルの形式を一行一行指定しています。もし、別の形式のファイルをフォルダー分けしたい場合は、ワード、テキスト、エクセルファイルを指定しているように指定すれば自動で移動ができます。

参考資料

0
1
0

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
0
1