Python os.rename() を使用してファイルとディレクトリの名前を変更する
Python ファイルの名前を変更
Python ファイルの名前を変更する ファイルまたはディレクトリの名前を変更するために使用される方法です。 Python プログラミング。 Python rename() ファイル メソッドは、src (ソース) と dst (宛先) という 2 つの引数を渡すことによって宣言できます。
構文
これは os.rename() メソッドの構文です
os.rename(src, dst)
Parameters
src: ソースはファイルまたはディレクトリの名前です。 すでに存在しているはずです。
夏時間: 「宛先」は、変更するファイルまたはディレクトリの新しい名前です。
例:
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()