LoginSignup
9
7

More than 5 years have passed since last update.

拡張子一括変換

Last updated at Posted at 2018-05-01

概要

「python 拡張子一括変換」で検索して出てくるサンプルが、欲しいものと違ったため作成。
備忘録的に投稿。
暗記できるくらい短いものが欲しかったので、↓を一番上にもってきときます。

コード - 暗記用

from pathlib import Path
for f in Path('.').rglob('*.docm'):
    f.rename(f.stem+'.doc')

pathlibのマニュアルを読んでたら、renameメソッドがあることに気がつきました。

その他の実装例

コード1 - 初回版

".docm" ⇒ ".doc"に決めうち変換。
ipythonでカレントディレクトリ変更したあと実行。

import pathlib
import shutil
files = list(pathlib.Path('.').rglob('*.docm'))
for i,f in enumerate(files):
    print("{0}/{1}".format(i+1,len(files)))
    shutil.copy(f, f.with_name(f.stem + ".doc"))

コード2 - コピー作らない版

というコメントがあったのでshutil.moveに書き換え

import pathlib
import shutil
files = list(pathlib.Path('.').rglob('*.docm'))
for i,f in enumerate(files):
    print("{0}/{1}".format(i+1,len(files)))
    shutil.move(f, f.with_name(f.stem + ".doc"))

コード3 - 進捗1行表示版

コード2(コピー作らない版)に加えて、Pythonで、進捗バーを自作する - naritoブログを参考に進捗を1行に表示。f-stringを利用。

import pathlib
import shutil
files = list(pathlib.Path('.').rglob('*.docm'))
prev_len=0
for i,src in enumerate(files):
    dest=src.with_suffix('.doc')
    print(f'\r{" "*prev_len}', end='') #前回の残像をスペースで消す
    progress=f'{i+1}/{len(files)}:{src.name} -> {dest.name}'
    print(f'\r{progress}',end='')
    shutil.move(src,dest)
    prev_len=len(progress)
print()

コード4 - @shiracamusさん版(関数化)

#!/usr/bin/env python3.6
# -*- coding:utf-8 -*-

import sys
import pathlib
import shutil

def rename_ext(path, ext_before, ext_after, verbose=True):
    files = list(pathlib.Path(path).rglob(f'*.{ext_before}'))
    total = len(files)
    for count, before in enumerate(files, 1):
        after = before.with_name(f'{before.stem}.{ext_after}')
        verbose and print(f'{count}/{total}: {before} -> {after}')
        shutil.move(before, after)

if __name__ == '__main__':
    cmd, *args = sys.argv
    if len(args) != 3:
        print(f'Usage: {cmd} <path> <ext_before> <ext_after>')
        sys.exit(1)
    rename_ext(*args)

参考

「python 拡張子一括変換」で検索して出てくるサンプル

Python - pythonで、ファイルの拡張子を変換してみたい。(11335) - teratail
Pythonでファイル名の前後に文字列や連番を加えて一括変更 Python _ note.nkmk.me
Pythonで複数のファイルの名前を一括変換する方法を教えてくだ... - Yahoo!知恵袋

作るときにみた記事

11.1. pathlib — オブジェクト指向のファイルシステムパス — Python 3.6.5 ドキュメント
Python - file, pathlibメモ - 何かできる気がする
Pythonで、進捗バーを自作する - naritoブログ

関連記事

フォルダごとに階層化されていたファイルをフラットにしながらコピーする - Qiita

9
7
2

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
9
7