LoginSignup
1
1

More than 5 years have passed since last update.

Python で Linux の rename コマンドを実装

Last updated at Posted at 2018-02-19

Homebrew の rename コマンドは高機能なんだけど、その分オプションが多くて覚えられない…
Linux みたいにシンプルな rename from to file... のコマンドが欲しいなあと思って Python で作ってみました。

環境

macOS Sierra 10.12.6
Python 2.7.10
Homebrew 1.5.4

実装

rename.py
import sys
import os

args = sys.argv
itext = args[1]
ftext = args[2]
files = set(args[3:])

for iname in files:
    fname = iname.replace(itext, ftext, 1)
    if fname != iname:
        if os.path.exists(fname):
            print("'"+iname+"' cannot be renamed to '"+fname+"'. '"+fname+"' has already existed.")
        else:
            os.rename(iname, fname)

GitHub からもダウンロードできます。

実行速度

10,000個のファイルを rename したときの実行速度を time コマンドで測定。

Homebrew Python
real 1.571 s 3.425 s
user 0.508 s 1.607 s
sys 0.832 s 1.091 s

結論

Python での rename コマンドの実装は処理速度の面で問題あり。
エイリアス alias rename="rename -s" で対応した方が良さそう。

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