Python でファイルの名前を変更する

Najwa Riyaz 2023年1月30日 Python Python File
  1. Python で os.rename() を使用してファイルの名前を変更する
  2. Python で shutil.move() を使用してファイルの名前を変更する
Python でファイルの名前を変更する

Python でファイルの名前を変更する場合は、次のいずれかのオプションを選択します。

  1. os.rename() を使用してファイルの名前を変更します。
  2. shutil.move() を使用してファイルの名前を変更します。

Python で os.rename() を使用してファイルの名前を変更する

関数 os.rename() を使用して、Python でファイルの名前を変更できます。

例えば、

Python
 pythonCopyimport os

file_oldname = os.path.join("c:\\Folder-1", "OldFileName.txt")
file_newname_newfile = os.path.join("c:\\Folder-1", "NewFileName.NewExtension")

os.rename(file_oldname, file_newname_newfile)

上記の例では、

file_oldname-古いファイル名。

file_newname_newfile-新しいファイル名。

結果:

  1. file_oldname という名前のファイルの名前が file_newname_newfile に変更されます
  2. file_oldname に存在していたコンテンツは、file_newname_newfile にあります。

前提条件:

Python で shutil.move() を使用してファイルの名前を変更する

関数 shutil.move() を使用して、Python でファイルの名前を変更することもできます。

例えば、

Python
 pythonCopyimport shutil

file_oldname = os.path.join("c:\\Folder-1", "OldFileName.txt")
file_newname_newfile = os.path.join("c:\\Folder-1", "NewFileName.NewExtension")

newFileName = shutil.move(file_oldname, file_newname_newfile)

print("The renamed file has the name:", newFileName)

上記の例では、

file_oldname:古いファイル名。

file_newname_newfile:新しいファイル名。

結果:

  1. file_oldname という名前のファイルの名前が file_newname_newfile に変更されます
  2. file_oldname に存在していたコンテンツが file_newname_newfile に表示されます。
  3. 戻り値-newFileName。これは新しいファイル名です。

前提条件:

チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe

関連記事 - Python File