LoginSignup
1
0

More than 3 years have passed since last update.

【Python3】画像の拡張子を一気に変更したいときに使えるコード

Posted at

備忘録やOUTPUT的な意味での蓄積

作成目的

作業用の拡張子をすべて変換したいときが定期的に起こったので、作業簡略化のために作成

作成環境

・windows10
・Anaconda3
・python3.7
・Jupyter Notebook

ドキュメント

①拡張子を変更したいフォルダ名を入力
②folderがなければcurrent_folder内に、[拡張子]_folderを作成する
③すでに同じフォルダ名がある場合、誤操作を防ぐためにErrorになる

※今回はpngに変換するコードを記載する

ライブラリの読み込み

All Necessary Libraries.py
import pathlib
import os
import shutil
import pprint
import numpy as np
from glob import glob
from PIL import Image
from tqdm import tqdm
from pathlib import Path

PG

change_pngextension_code
# フォルダ名を入力
folder_name = input('Enter the folder name :')
p, new_folder_name = Path('C:/Users/H3051411/OUT/' + folder_name), '_png_folder'
# 現在のpathから新しいpng_folderを作成
new_folder_path = os.path.join(p, new_folder_name)
#print(new_folder_path)(必要があれば確認)

# フォルダがなければコピーして作成
if not os.path.exists(new_folder_path):
    # ディレクトリ内のファイルを取得
    shutil.copytree(p, new_folder_path)

    # 新たなpathの拡張子をpngファイルに変換
    new_p = Path(new_folder_path)
    files = list(new_p.glob('*.*'))

    for i,f in tqdm(enumerate(files)):
        print('画像変換数:{0}/{1}'.format(i+1,len(files))
        shutil.move(f, f.with_name(f.stem + ".png"))

else:
    print('すでにfolderが存在します.')

課題

・関数化していない
・画像数が増えると時間かかりそう(未テスト)

まとめ

作業時間が1時間から1分になりました。
あと、もっといい書き方がある気がする。

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