工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

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」に変更しました。

これが完全なコードです

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

  1. Python のキーワードと識別子
  2. Python ステートメント、インデント、およびコメント
  3. Python 変数、定数、およびリテラル
  4. Python の型変換と型キャスト
  5. Python の入力、出力、およびインポート
  6. Python グローバル変数、ローカル変数、および非ローカル変数
  7. Python ファイル I/O
  8. Python ディレクトリおよびファイル管理
  9. Python エラーと組み込み例外
  10. try、except、finally ステートメントを使用した Python 例外処理
  11. Python Average:Python でリストの AVERAGE を見つける方法