Skip to content

Instantly share code, notes, and snippets.

@castaneai
Created February 17, 2014 17:35
Show Gist options
  • Save castaneai/9055276 to your computer and use it in GitHub Desktop.
Save castaneai/9055276 to your computer and use it in GitHub Desktop.
ファイルを拡張子に応じてディレクトリに分別して整理するスクリプト
# -*- coding: utf8 -*-
import os
import shutil
dir = os.getcwd()
rules = {
u"画像": [".jpg", ".png", ".gif"],
u"音楽": [".mp3", ".m4a"],
}
def get_dest_dirname(ext):
for dirname, exts in rules.items():
if ext in exts:
return dirname
return None
for filename in os.listdir(dir):
ext = os.path.splitext(filename)[1]
dest_dirname = get_dest_dirname(ext)
if dest_dirname is not None:
print(u"{0}の振り分け先は{1}です.".format(filename, dest_dirname))
src_path = u"{0}/{1}".format(dir, filename)
dest_dir_path = u"{0}/{1}".format(dir, dest_dirname)
dest_path = u"{0}/{1}".format(dest_dir_path, filename)
if not os.path.exists(dest_dir_path):
os.mkdir(dest_dir_path)
shutil.move(src_path, dest_path)
@castaneai
Copy link
Author

Windowsにて,ファイル名にハートマークなどのSJIS以外の文字?が入っていた場合,unicode errorが発生する不具合が確認された.対策が今のところ思いつかない.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment