【python】ファイル名のコピーと名前の変更【ChatGPT】

ファイル名を4桁の数字に付け替えるプログラム。
日本語のファイルだとうまくpythonで扱えない時があるのでその対策。


import os
import shutil

# ディレクトリ名とコピー先のディレクトリ名を指定
dir_name = "元のディレクトリ名"
copy_dir_name = "コピー先のディレクトリ名"

# copy_dir_nameが存在しない場合は作成
if not os.path.exists(copy_dir_name):
os.makedirs(copy_dir_name)

# ディレクトリ内のファイル一覧を取得
files = os.listdir(dir_name)

# ファイルの数を取得
num_files = len(files)

# 4桁の数字の初期値
num = 1

# ファイルを順にコピー
for file in files:
# コピー元のファイルパスを作成
src_path = os.path.join(dir_name, file)

# コピー先のファイルパスを作成
dst_name = f"{num:04}.jpg" # 4桁の数字を作成
dst_path = os.path.join(copy_dir_name, dst_name)

# ファイルをコピー
shutil.copy(src_path, dst_path)

# 数字を1つ増やす
num += 1

# コピーが終了したら完了メッセージを表示
print(f"{num_files} files were copied and renamed.")

sciencompass34 has written 159 articles

はじめまして!”あおやぎ”と言います。
メーカーで研究開発の仕事をしています。このブログでは、私の専門分野である半導体やそれに関連する内容を紹介していきます。
半導体関連の知識をまとめたデータベースのようにしたいなと思っています。

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください