ファイル名で振り分け
ぱいそん
じじぃ~専用 覚え書き
HDD の ファイルを 特定条件で
振り分ける方法
例 huriwake.py
# テキストデータ 【*.TXT】を
# C:\text\file内に「キーワード」に従いフォルダを作成し
# 同一「キーワード」に該当するファイルを
# サブフォルダにMoveする。
# =============== import
from pathlib import Path
import shutil
import os
# =============== 変数定義
target_path = 'C:\\text\\file'
# =============== CD チェンジディレクトリ
os.chdir(target_path)
cwd = os.getcwd()
print(cwd)
# =============== 基本(コピー元 ディレクトリの設定)
dir_path = (target_path)
# =============== 引数だけ「あり」な関数
# =============== 処理対象ファイルの指定 *.TXT
def file_move(text):
# ここが 関数の本文(実行する内容)
print(text)
os.makedirs((text), exist_ok=True)
# 文字列 振り分け 先頭位置
x_files = Path(dir_path).glob((text)+'*.txt')
# 文字列 振り分け 任意位置
# x_files = Path(dir_path).glob('*'+(text)+'*.txt')
for file in x_files:
shutil.move((file), (text)+'/')
# =============== 振り分けするための サブフォルダ名の定義
# =============== 同時に振り分けのための「キーワード」の定義
# ひながた file_move('')
# *.TXT用 先頭位置文字列
# file_move('')
file_move('abc')
file_move('xyz')
# file_move('hhh_ ') #★半角スペースが末尾に入るとNG
file_move('hhh_')
file_move('ラズベリーパイ')
file_move('振り分け条件')
file_move('クリスマス')
# =============== 処理対象ファイルの指定 *.BMP
def file_move(text):
# ここが 関数の本文(実行する内容)
print(text)
os.makedirs((text), exist_ok=True)
# 文字列 振り分け 先頭位置
# x_files = Path(dir_path).glob((text)+'*.txt')
# 文字列 振り分け 任意位置
x_files = Path(dir_path).glob('*'+(text)+'*.txt')
for file in x_files:
shutil.move((file), (text)+'/')
# print(text)
# =============== 任意位置のキーワード振り分け
# ひながた file_move('')
file_move('Python')
file_move('Arduino')
file_move('FileSum')
file_move('氷河')
file_move('自動車')
file_move('DSCF')
# ==========================================================
folder_names = [
'0_to_9',
'A_to_Z',
'あいうえお',
'アイウエオ'
]
# ==========================================================
for folder_name in folder_names:
# os.mkdir(folder_name)
os.makedirs((folder_name), exist_ok=True)
# os.makedirs('./2018年', exist_ok=True)
x_files = Path(dir_path).glob('[0-9]*.txt')
for file in x_files:
shutil.move((file), "0_to_9/")
x_files = Path(dir_path).glob('[a-z]*.txt')
for file in x_files:
shutil.move((file), "A_to_Z/")
x_files = Path(dir_path).glob('[あ-ん]*.txt')
for file in x_files:
shutil.move((file), "あいうえお/")
x_files = Path(dir_path).glob('[ア-ン]*.txt')
for file in x_files:
shutil.move((file), "アイウエオ/")
# =============== END END END
'''