LoginSignup
0
0

【Python】`001_sample.json`と同じ中身のファイルを100個、連番で瞬時に作成する方法

Last updated at Posted at 2023-06-27

概要

  • 001_sample.jsonというファイルがあったとします。中身を全く同じ状態のまま、100_sample.jsonまでファイルをコピー&連番で命名させる方法を紹介します。

サンプルコード解説

  • サンプルコードでは、shutilモジュールを使用してファイルのコピーを行います。
sample.py
import shutil

# ファイルのコピー元とコピー先のパスを指定
source_file = "001_sample.json"
destination_directory = "./"

# 100回ループしてファイルをコピー
for i in range(2, 100):
    # コピー先のファイル名を生成
    destination_file = f"{str(i).zfill(3)}_sample.json"
    # ファイルをコピー
    shutil.copyfile(source_file, destination_directory + destination_file)
  • source_file変数に元となるファイルのパスを指定
  • destination_directory変数にコピー先のディレクトリのパスを指定(この例ではカレントディレクトリ)
  • 1から100までの範囲でループを回し、f"{str(i).zfill(3)}_request.sh"を使用してコピー先のファイル名を生成
    • zfill(3)は、生成されるファイル名が常に3桁のゼロパディングされることを保証
  • 最後に、shutil.copyfileを使用してファイルをコピー。

備忘録

  • osモジュールを使用する方法もあると思います。
  • shutil.copyfile()関数は、ソースファイルと宛先ファイルのパスを指定するだけで、簡単にファイルをコピーできるのが良いですよね。パスの組み立てやファイルのオープン・クローズなどの手間が不要です。
0
0
1

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