CodeGym /행동 /Python SELF KO /디렉토리 작업

디렉토리 작업

Python SELF KO
레벨 21 , 레슨 6
사용 가능

7.1 기본 작업

파일 작업을 익혔으니 이제 디렉토리 작업을 해보자. 때때로 파일 작업과 비슷하지만, 때로는 그렇지 않다. 디렉토리에는 고유한 특성이 있다. 디렉토리 작업을 위한 기본 함수들은 모듈 osshutil이 제공한다.

디렉토리 작업의 기본 작업:

디렉토리 생성

새로운 디렉토리를 생성하려면 os.mkdir() 함수를 사용한다.

예시:


import os

# 새 디렉토리 생성
os.mkdir('new_directory')
print("디렉토리 'new_directory' 생성됨")

여러 중첩 디렉토리 생성

여러 중첩 디렉토리를 생성하려면 os.makedirs() 함수를 사용한다.

예시:


import os

# 여러 중첩 디렉토리 생성
os.makedirs('parent_directory/child_directory')
print("중첩 디렉토리 'parent_directory/child_directory' 생성됨")

디렉토리 삭제

빈 디렉토리를 삭제하려면 os.rmdir() 함수를 사용한다. 내용이 있는 디렉토리를 삭제하려면 shutil.rmtree() 함수를 사용한다.

예시:


import os

# 빈 디렉토리 삭제
os.rmdir('new_directory')
print("디렉토리 'new_directory' 삭제됨")

내용이 있는 디렉토리 삭제 예시:


import shutil

# 내용이 있는 디렉토리 삭제
shutil.rmtree('parent_directory')
print("디렉토리 'parent_directory' 및 모든 내용 삭제됨")

중요! 절대 모든 내용을 가진 디렉토리를 삭제하지 마세요. 10번 중 한 번은 프로그램에 버그가 생겨 디스크의 절반 파일을 삭제하게 됩니다. 누구나 그 과정을 겪습니다. 절대 그렇게 하지 마세요.

디렉토리를 삭제하기 전에 os.path.exists() 함수를 사용하여 존재 여부를 확인하는 것이 좋습니다. 이는 존재하지 않는 디렉토리를 삭제하거나 잘못된 경로와 관련된 오류를 방지할 수 있습니다.

예시:


import os
import shutil

# 삭제 전에 디렉토리 존재 여부 확인
directory_path = 'parent_directory'
if os.path.exists(directory_path):
    shutil.rmtree(directory_path)
    print(f"디렉토리 '{directory_path}' 및 모든 내용이 삭제됨")
else:
    print(f"디렉토리 '{directory_path}' 존재하지 않음, 삭제 불가")

7.2 디렉토리 복사

디렉토리 이동 및 이름 변경

디렉토리를 이동하거나 이름을 변경하려면 os.rename() 함수를 사용한다.


import os

# 예제를 위한 디렉토리 생성
os.mkdir('original_directory')

# 디렉토리 이름 변경
os.rename('original_directory', 'renamed_directory')
print("디렉토리 'original_directory'가 'renamed_directory'로 변경됨") 

디렉토리 복사

디렉토리를 복사하려면 shutil.copytree() 함수를 사용한다. 이 함수는 디렉토리 내용을 복사할 뿐만 아니라 지정된 대상 경로에 새 디렉토리도 생성한다.


import os
import shutil

# 예제를 위한 디렉토리 생성
os.mkdir('source_directory')

# 디렉토리 복사
shutil.copytree('source_directory', 'destination_directory')
print("디렉토리 'source_directory'가 'destination_directory'로 복사됨")

7.3 현재 디렉토리

실행 중인 각 프로그램에는 "현재 작업 디렉토리"라는 개념이 있습니다. 일반적으로 프로그램이 실행되는 디렉토리로, 프로그램의 보조 파일을 찾는 곳입니다. 예를 들어 디렉토리 이름 없이 경로가 지정된 모든 파일은 현재 디렉토리에서 찾습니다.

현재 작업 디렉토리 얻기

현재 작업 디렉토리를 얻으려면 os.getcwd() 함수를 사용한다.


import os

# 현재 작업 디렉토리 얻기
current_directory = os.getcwd()
print(f"현재 작업 디렉토리: {current_directory}")

현재 작업 디렉토리 변경

현재 작업 디렉토리를 변경하려면 os.chdir() 함수를 사용한다.


import os

# 현재 작업 디렉토리 변경
os.chdir('new_directory')
print(f"현재 작업 디렉토리가 변경됨: {os.getcwd()}")

현재 작업 디렉토리를 변경하면 현재 디렉토리를 기준으로 지정된 파일 경로에 영향을 줄 수 있습니다. 디렉토리를 변경할 때 주의하세요. 프로그램이 원래 디렉토리에 파일을 기대하는 경우 오류가 발생할 수 있습니다.

디렉토리 존재 여부 확인

디렉토리가 존재하는지 확인하려면 os.path.exists() 함수를 사용한다.


import os

# 디렉토리 존재 여부 확인
directory_path = 'new_directory'
if os.path.exists(directory_path):
    print(f"디렉토리 '{directory_path}' 존재함")
else:
    print(f"디렉토리 '{directory_path}' 존재하지 않음")

디렉토리의 절대 경로 얻기

절대 경로를 얻으려면 os.path.abspath() 함수를 사용한다.


import os

# 디렉토리의 절대 경로 얻기
relative_path = 'example_directory'
absolute_path = os.path.abspath(relative_path)
print(f"절대 경로: {absolute_path}")

7.4 디렉토리 내용

파일 및 디렉토리 목록 얻기

지정된 디렉토리에서 파일 및 디렉토리 목록을 얻으려면 os.listdir() 함수를 사용한다.


import os

# 현재 디렉토리의 파일 및 디렉토리 목록 얻기
contents = os.listdir('.')
print(f"현재 디렉토리의 내용: {contents}")

파일 및 디렉토리를 경로 목록이 아닌 복잡한 객체로 다루는 것이 가능하다.

os.scandir()를 사용하여 디렉토리 내용 정보 얻기

os.scandir() 함수는 디렉토리의 각 항목에 대한 DirEntry 객체를 반환하는 이터레이터를 반환합니다. 이 객체들은 파일 및 디렉토리에 대한 정보를 포함하고 있어 특히 큰 디렉토리의 경우 os.listdir()보다 더 효율적인 사용이 가능합니다.


import os

# 디렉토리 내용 정보 얻기
with os.scandir('.') as entries:
    for entry in entries:
        print(f"이름: {entry.name}, 디렉토리 여부: {entry.is_dir()}, 파일 여부: {entry.is_file()}")
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION