0
0

手元でちょろっとファイル名を一括更新したい

Posted at

やりたいこと

  • 特定のディレクトリ直下にあるファイル名を一括変換したい
  • ファイル名に含まれる特定の文字列を特定の文字列へ変換したい
  • 手動でぽちぽちするのも面倒だが、エディタを立ち上げてプログラムを組むほどではない
  • ターミナルで完結したい

イメージはこんな感じ↓

変換前
target-directory
    |-単体試験仕様書_abc.xlsx
    |-単体試験仕様書_def.xlsx
    |-単体試験仕様書_ghi.xlsx
    |-単体試験仕様書_jkl.xlsx
    |-単体試験仕様書_mln.xlsx
    |-単体試験仕様書_opq.xlsx
    |-単体試験仕様書_rst.xlsx
上司「単体試験仕様書じゃなくて、単体テスト仕様書に全部直しておいて」
target-directory
    |-単体試験テスト_abc.xlsx
    |-単体試験テスト_def.xlsx
    |-単体試験テスト_ghi.xlsx
    |-単体試験テスト_jkl.xlsx
    |-単体試験テスト_mln.xlsx
    |-単体試験テスト_opq.xlsx
    |-単体試験テスト_rst.xlsx

ターミナルからPythonを起動する

早速お仕事をしていきましょう。
PCにPython3がインストールされており、Pythonにファイルの書き込み権限が付与されていることが前提です。

1. pythonを起動する

targetf-directory $ python
Python 3.12.2 (main, Feb 21 2024, 01:35:03) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

2. ファイル名を取得

>>> files = os.listdir()
>>> files
['単体試験仕様書_abc.xlsx', '単体試験仕様書_def.xlsx', '単体試験テスト_ghi.xlsx', '単体試験テスト_jkl.xlsx', '単体試験テスト_mln.xlsx', '単体試験テスト_opq.xlsx', '単体試験テスト_rst.xlsx']

3.for文で一括変換

>>> for file in files:
...     os.rename('./'+file,'./'+file.replace('単体試験','単体テスト'))

以上です!

0
0
4

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
0