logo

パイソン | os.rename() メソッド

OSモジュール Python では、オペレーティング システムと対話するための関数が提供されます。 OS は Python の標準ユーティリティ モジュールに含まれます。このモジュールは、オペレーティング システムに依存する機能を使用するポータブルな方法を提供します。

Python でファイルまたはディレクトリの名前を変更するには、次を使用できます os.rename() OSモジュールの機能。このメソッドは、ソース ファイルまたはディレクトリの名前を、指定された宛先ファイルまたはディレクトリに変更します。 2 つのパラメータを取ります – ソース (現在のファイル名) と 行き先 (新しいファイル名)。



構文 :

os.rename(ソース、宛先、*、src_dir_fd = なし、dst_dir_fd = なし)

パラメーター:

  • ソース: ファイル システム パスを表すパスのようなオブジェクト。これは、名前を変更するソース ファイルのパスです。
  • 行き先: ファイル システム パスを表すパスのようなオブジェクト。
  • src_dir_fd (オプション): ディレクトリを参照するファイル記述子。
  • dst_dir_fd (オプション): ディレクトリを参照するファイル記述子。

戻り値の型:

このメソッドは値を返しません。

os.rename() 関数の使用とエラー処理:

の os.rename 関数の使い方をプログラムで見てみましょう。 OSモジュール 使用中のエラーの処理方法についても説明します。



コード 1: の使用 os.rename() 方法。

Python3






# Python program to explain os.rename() method> # importing os module> import> os> # Source file path> source>=> 'techcodeview.com/file.txt'> # destination file path> dest>=> 'GeekforGeeks/newfile.txt'> # Now rename the source path> # to destination path> # using os.rename() method> os.rename(source, dest)> print>('Source path renamed to destination path successfully.')>

>

インターネットブラウザの設定
>

コード 2: 考えられるエラーの処理

Python3




# Python program to explain os.rename() method> # importing os module> import> os> # Source file path> source>=> './techcodeview.com/file.txt'> # destination file path> dest>=> './techcodeview.com/dir'> # try renaming the source path> # to destination path> # using os.rename() method> try> :> >os.rename(source, dest)> >print>('Source path renamed to destination path successfully.')> # If Source is a file> # but destination is a directory> except> IsADirectoryError:> >print>('Source>is> a>file> but destination>is> a directory.')> # If source is a directory> # but destination is a file> except> NotADirectoryError:> >print>('Source>is> a directory but destination>is> a>file>.')> # For permission related errors> except> PermissionError:> >print>('Operation>not> permitted.')> # For other errors> except> OSError as error:> >print>(error)>

Javaブール値

>

>

参考資料: https://docs.python.org/3/library/os.html#os.rename

この記事では、Python で os.rename() 関数を使用してファイルまたはディレクトリの名前を変更する方法について説明しました。これは、Python でファイルまたはディレクトリの名前を変更する非常に簡単で簡単な方法です。 OS モジュールは、オペレーティング システムとの対話に使用される関数のリストを提供します。