heywantodo 2023. 7. 6. 11:20
728x90
반응형

[Python] OS

Python의 OS 모듈은 운영 체제와 상호 작용 하기 위한 다양한 기능을 제공하는 모듈이다.

파일 및 디렉토리 관리, 프로세스 제어, 환경 변수 액세스 등과 같은 운영 체제 수준의 작업을 수행할 수 있다.

 

먼저 모듈을 import 하자

import os

 

1. 디렉토리 관리

  • 디렉토리 생성
os.mkdir("new_directory")
  • 디렉토리 내용 확인
contents = os.listdir(".")
print(contents)
  • 현재 작업 디렉토리 확인
current_dir = os.getcwd()
print(current_dir)
  • 작업 디렉토리 변경
os.chdir("new_directory")
updated_dir = os.getcwd()
print(updated_dir)
  • 디렉토리 삭제
os.rmdir("new_directory")

 

2. 파일 관리

  • 파일 삭제
os.remove("file.txt")
  • 파일 이름 변경
os.rename("old_name.txt", "new_name.txt")
  • 파일 또는 디렉토리의 존재 확인
file_exist = os.path.exists("file.txt")
print(file_exists)
  • 파일인지 확인
is_file = os.path.isfile("file.txt")
print(is_file)
  • 디렉토리인지 확인

 

3. 프로세스 제어

  • 운영 체제의 셸에서 명령 실행
os.system("ls -l")
  • 파일 열기
os.startfile("document.pdf")

 

4. 환경 변수 액세스

  • 현재 시스템의 환경 변수 딕셔너리
env_vars = os.environ
print(env_vars)
  • 특정 환경 변수 값 확인
java_home = os.getenv("JAVA_HOME")
print(java_home)

 

위와 같이 os 모듈을 사용하면 운영 체제 관련 작업을 효율적으로 수행할 수 있다.

 

 

728x90
반응형