LoginSignup
0
2

More than 3 years have passed since last update.

[python] 画像ファイル名を連番に変える

Posted at

やりたいこと

画像のファイル名を連番に変える。
[変更前]
a.jpg
b.jpg
c.jpg
[変更後]
0001.jpg
0002.jpg
0003.jpg

準備

・pythonは既にインストールしている前提
・名前を連番にしたい画像を任意のフォルダ(今回はimage)に集める

コードを作成

import os
import glob

files = glob.glob('image/*')

for idx, f in enumerate(files):
    ftitle, fext = os.path.splitext(f)
    os.rename(f, format(idx, '04d')+fext)

1.imageフォルダ内の画像の名前を取得

files = glob.glob('image/*')

2.画像分だけ名前変更処理を繰り返す

for idx, f in enumerate(files):

enumrateによりidxには数字が入り、forで繰り返すたびに数字が1ずつ繰り上がります。

3.ファイル名を分解

ftitle, fext = os.path.splitext(f)

ftitle:ファイル名 ftext:拡張子
例えば、a.jpgならftitleには「a」、ftextには「.jpg」が入ります。

4.ファイル名を変更

os.rename(f, format(idx, '04d')+fext)
0
2
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
0
2