Python で os.rename() を使用してファイルとディレクトリの名前を変更する
Python リネーム ファイル
Python rename() ファイル は、Python プログラミングでファイルまたはディレクトリの名前を変更するために使用される方法です。 Python rename() ファイル メソッドは、src (ソース) と dst (宛先) という名前の 2 つの引数を渡すことで宣言できます。
構文
これは os.rename() メソッドの構文です
os.rename(src, dst)
パラメータ
ソース: ソースは、ファイルまたはディレクトリの名前です。既に存在している必要があります。
dst: Destination は、変更するファイルまたはディレクトリの新しい名前です。
例:
import os os.rename('guru99.txt','career.guru99.txt')
例を詳しく見てみましょう
元のファイルの名前を変更できます。ファイル名を「Guru99.txt」から「Career.guru99.txt」に変更しました。
- 「guru99.txt」ファイルの名前を変更するには、OS モジュールの「名前変更機能」を使用します
- コードが実行されると、パネルの右側に新しいファイル「career.guru99.txt」が作成され、元のファイルの名前を変更したことがわかります。
これが完全なコードです
import os import shutil from os import path def main(): # make a duplicate of an existing file if path.exists("guru99.txt"): # get the path to the file in the current directory src = path.realpath("guru99.txt"); # rename the original file os.rename('guru99.txt','career.guru99.txt') if __name__ == "__main__": main()
Python