logo

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()>방법.




int를 double java로 변환
# 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이 사용됩니다.
존재_확인(선택사항): 이 매개변수에는 기본값 False가 사용됩니다. 대상 디렉터리가 이미 존재하는 경우 해당 값이 False이면 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>