Pythonでディレクトリを作成する

Python の OS モジュールは、オペレーティング システムと対話するための機能を提供します。 OS は Python の標準ユーティリティ モジュールに含まれます。このモジュールは、オペレーティング システムに依存する機能を使用するポータブルな方法を提供します。の os> そして os.path> モジュールには、ファイル システムと対話するための多くの関数が含まれています。 OSモジュールのすべての関数が発生します OSError> ファイル名とパスが無効またはアクセスできない場合、またはその他の引数が正しい型であるにもかかわらずオペレーティング システムで受け入れられない場合。

OS モジュールでは、ディレクターを作成するためにさまざまな方法を使用できます。これらは -

os.mkdir() の使用

os.mkdir()> Python のメソッドは、指定された数値モードで path という名前のディレクトリを作成するために使用されます。このメソッドは上げます FileExistsError> 作成するディレクトリがすでに存在する場合。

構文: os.mkdir(パス、モード = 0o777、*、dir_fd = なし)

パラメータ:
パス: ファイル システム パスを表すパスのようなオブジェクト。パスのようなオブジェクトは、パスを表す文字列またはバイト オブジェクトです。
モード (オプション): 作成されるディレクトリのモードを表す整数値。このパラメータを省略すると、デフォルト値 Oo777 が使用されます。
dir_fd (オプション): ディレクトリを参照するファイル記述子。このパラメータのデフォルト値は「なし」です。
指定されたパスが絶対パスの場合、dir_fd は無視されます。

注記: パラメータ リストの「*」は、後続のすべてのパラメータ (ここでは「dir_fd」) がキーワード専用パラメータであり、位置パラメータとしてではなく名前を使用して指定できることを示します。

戻り値の型: このメソッドは値を返しません。

例 #1: の使用 os.mkdir()> ディレクトリ/ファイルを作成する方法




# Python program to explain os.mkdir() method> > # importing os module> import> os> > # Directory> directory> => 'techcodeview.com'> > # Parent Directory path> parent_dir> => 'D:/Pycharm projects/'> > # Path> path> => os.path.join(parent_dir, directory)> > # Create the directory> # 'GeeksForGeeks' in> # '/home / User / Documents'> os.mkdir(path)> print> (> 'Directory '% s' created'> %> directory)> > # Directory> directory> => 'Geeks'> > # Parent Directory path> parent_dir> => 'D:/Pycharm projects'> > # mode> mode> => 0o666> > # Path> path> => os.path.join(parent_dir, directory)> > # Create the directory> # 'GeeksForGeeks' in> # '/home / User / Documents'> # with mode 0o666> os.mkdir(path, mode)> print> (> 'Directory '% s' created'> %> directory)>

出力:

 Directory 'techcodeview.com' created Directory 'Geeks' created 

例2: 使用中のエラー os.mkdir()> 方法。




# Python program to explain os.mkdir() method> > # importing os module> import> os> > # Directory> directory> => 'GeeksForGeeks'> > # Parent Directory path> parent_dir> => 'D:/Pycharm projects/'> > # Path> path> => os.path.join(parent_dir, directory)> > # Create the directory> # 'GeeksForGeeks' in> # '/home / User / Documents'> os.mkdir(path)> print> (> 'Directory '% s' created'> %> directory)> > # if directory / file that> # is to be created already> # exists then 'FileExistsError'> # will be raised by os.mkdir() method> > # Similarly, if the specified path> # is invalid 'FileNotFoundError' Error> # will be raised>

出力:

 Traceback (most recent call last): File 'gfg.py', line 18, in os.mkdir(path) FileExistsError: [WinError 183] Cannot create a file when that file / /already exists: 'D:/Pycharm projects/GeeksForGeeks' 

例 #3: 使用中のエラー処理 os.mkdir()> 方法。




# Python program to explain os.mkdir() method> > # importing os module> import> os> > # path> path> => 'D:/Pycharm projects / GeeksForGeeks'> > # Create the directory> # 'GeeksForGeeks' in> # '/home / User / Documents'> try> :> > os.mkdir(path)> except> OSError as error:> > print> (error)>

出力:

 [WinError 183] Cannot create a file when that file/ /already exists: 'D:/Pycharm projects/GeeksForGeeks' 

os.makedirs() の使用

os.makedirs()> Python のメソッドは、ディレクトリを再帰的に作成するために使用されます。つまり、リーフ ディレクトリの作成中に中間レベルのディレクトリが欠落している場合、 os.makedirs()> メソッドはそれらをすべて作成します。
たとえば、次のパスを考えてみましょう。

 D:/Pycharm projects/GeeksForGeeks/Authors/Nikhil 

ディレクトリ「Nikhil」を作成したいが、ディレクトリ「GeeksForGeeks」と「Authors」がパス内で使用できないとします。それから os.makedirs()> このメソッドは、指定されたパスに使用できないディレクトリまたは欠落しているディレクトリをすべて作成します。最初に「GeeksForGeeks」と「Authors」が作成され、次に「Nikhil」ディレクトリが作成されます。

構文: os.makedirs(パス、モード = 0o777、exist_ok = False)

パラメータ:
パス: ファイル システム パスを表すパスのようなオブジェクト。パスのようなオブジェクトは、パスを表す文字列またはバイト オブジェクトです。
モード (オプション): 新しく作成されたディレクトリのモードを表す整数値。このパラメータを省略すると、デフォルト値 Oo777 が使用されます。
存在_ok (オプション): このパラメータにはデフォルト値 False が使用されます。ターゲット ディレクトリがすでに存在する場合、その値が False の場合は OSError が発生し、それ以外の場合は OSError が発生します。

戻り値の型: このメソッドは値を返しません。

例 #1: の使用 os.makedirs()> ディレクトリを作成するメソッド。




# Python program to explain os.makedirs() method> > # importing os module> import> os> > # Leaf directory> directory> => 'Nikhil'> > # Parent Directories> parent_dir> => 'D:/Pycharm projects/GeeksForGeeks/Authors'> > # Path> path> => os.path.join(parent_dir, directory)> > # Create the directory> # 'Nikhil'> os.makedirs(path)> print> (> 'Directory '% s' created'> %> directory)> > # Directory 'GeeksForGeeks' and 'Authors' will> # be created too> # if it does not exists> > > > # Leaf directory> directory> => 'c'> > # Parent Directories> parent_dir> => 'D:/Pycharm projects/techcodeview.com/a/b'> > # mode> mode> => 0o666> > path> => os.path.join(parent_dir, directory)> > # Create the directory 'c'> > os.makedirs(path, mode)> print> (> 'Directory '% s' created'> %> directory)> > > # 'GeeksForGeeks', 'a', and 'b'> # will also be created if> # it does not exists> > # If any of the intermediate level> # directory is missing> # os.makedirs() method will> # create them> > # os.makedirs() method can be> # used to create a directory tree>

出力:

 Directory 'Nikhil' created Directory 'c' created 

例2:




# Python program to explain os.makedirs() method> > # importing os module> import> os> > # os.makedirs() method will raise> # an OSError if the directory> # to be created already exists> > > # Directory> directory> => 'Nikhil'> > # Parent Directory path> parent_dir> => 'D:/Pycharm projects/GeeksForGeeks/Authors'> > # Path> path> => os.path.join(parent_dir, directory)> > # Create the directory> # 'Nikhil'> os.makedirs(path)> print> (> 'Directory '% s' created'> %> directory)>

出力:

 Traceback (most recent call last): File 'gfg.py', line 22, in os.makedirs(path) File 'C:UsersNikhil AggarwalAppDataLocalProgramsPython/ / Python38-32libos.py', line 221, in makedirs mkdir(name, mode) FileExistsError: [WinError 183] Cannot create a file when that/ / file already exists: 'D:/Pycharm projects/GeeksForGeeks/AuthorsNikhil' 

例 #3: os.makedirs() メソッド使用時のエラーの処理。




# Python program to explain os.makedirs() method> > # importing os module> import> os> > # os.makedirs() method will raise> # an OSError if the directory> # to be created already exists> # But It can be suppressed by> # setting the value of a parameter> # exist_ok as True> > # Directory> directory> => 'Nikhil'> > # Parent Directory path> parent_dir> => 'D:/Pycharm projects/GeeksForGeeks/Authors'> > # Path> path> => os.path.join(parent_dir, directory)> > # Create the directory> # 'Nikhil'> try> :> > os.makedirs(path, exist_ok> => True> )> > print> (> 'Directory '%s' created successfully'> %> directory)> except> OSError as error:> > print> (> 'Directory '%s' can not be created'> %> directory)> > # By setting exist_ok as True> # error caused due already> # existing directory can be suppressed> # but other OSError may be raised> # due to other error like> # invalid path name>

出力:

 Directory 'Nikhil' created successfully