본문 바로가기
Python

[Python] os 모듈의 함수들 : file과 directory 관련

by ds31x 2023. 7. 4.
728x90

os 모듈의 함수들 : file과 directory 관련

os

  • operating system (운영체제)와
  • 상호작용을 위한 다양한 기능을 제공하는
  • built-in module임.

대부분 os 종속적인 기능들이다.


os.path 모듈

ds_exist = os.path.exists('path')
  • path가 실제로 존재하는 파일 또는 디렉토리인 경우, True를 반환, 아니면 False

is_file = os.path.isfile('file_path')
  • file_path가 파일인 경우, True를 반환, 아니면 False
  • hard link인 경우에도 True를 반환.

is_dir = os.path.isdir('dir_path')
  • dir_path가 디렉토리인 경우, True를 반환, 아니면 False

ret_path = os.path.join('path0','path1','path2')
  • argument로 넘어온 문자열들을 순서대로 붙여서 하나의 path를 만들어냄.
  • system에서 file 또는 directory의 path를 지정하는 방식에 맞춰 구분자를 들어가게 됨.

path_tuple = os.path.split('/home/dsaint31/lecture')
  • argument로 주어진 path를 2개로 나누어줌. (말단과 말단을 포함한 디렉토리 경로로)
  • 위의 예에서 lecture는 디렉토일수도 파일일수도 있음.
  • 위의 예의 결과는 다음과 같음 : ('/home/dsaint31', 'lecture')

is_slink = os.path.islink('link_file_path')
  • argument로 넘어온 path가 symbolic link인지 여부를 반환.
  • hard link의 경우엔 False를 반환한다.

src_path = os.path.realpath('link_file_path')
  • symbolic link파일의 원본의 위치를 반환.

abs_path = os.path.abspath('target_path')
  • absolute path를 반환해줌.

dir_path = os.path.dirname('file_path')
  • argument의 path를 포함하는 directoroy의 path를 반환.

base_name = os.path.basename('/path0/path1/path.txt')
  • argument로 주어진 경로 중 말단의 이름(확장자 있을시 포함됨)을 반환

size = os.path.getsize('target_path')
  • 파일의 크기를 반환.

os.path 도 많이 사용되나 불편한 점이 있다보니
Python 3.4에 추가된 pathlib 모듈도 많이 사용된다.
https://ds31x.tistory.com/233

 

[Python] pathlib.Path 사용하기.

Path 모듈은 file 및 directory의 path 를 객체지향적으로 취급하기 쉬운 인터페이스를 제공하는 Python 표준 라이브러리임. Python 3.4 이상에서 사용가능함. Path 인스턴스 생성. from pathlib import Path # current

ds31x.tistory.com


os 모듈

ds_cwd_path = os.getcwd()
  • current working directory를 반환.

os.chdir('new_cwd')
  • cwd를 변경함.

os.rename('old_name.txt', 'new_name.txt')
  • 파일의 이름 변경.
  • os.replace 도 같은 역할을 해줌.

os.chmod('target_file_path', 0o400)
  • linux의 chmod에 대한 python 구현물.
  • read : 4 ,write :2 , execute :1 로 처리되는 chmod와 동일.
  • permission을 지정하는데에 base-8을 주로 이용함.

uid = 3   # linux 등에서 확인하고 해당 user의 uid값을 넣어줘야 함.
gid = 30  # linux 등에서 확인하고 해당 group의 gid값을 넣어줘야 함
os.chown('target_file_path', uid, gid)
  • chown과 유사함.

linux에서는 id 명령어로 uid와 gid를 확인 가능함.
echo $UID로도 확인 가능함.


os.remove('file_path_to_del')
  • argument에 해당하는 file을 삭제

os.rmdir('dir_path_to_del')
  • argument에 해당하는 directory을 삭제
  • 지울 디렉토리가 존재하지 않거나, 비어있는 디렉토리가 아닌 경우, FileNotFoundError를 발생시킴.

사용하기 불편해서 shutil.rmtree()를 보다 많이 이용함.


os.removedirs('dir_path_to_del')
  • 내부의 subdirectory삭제에 이용됨.
  • 문제는 지울 디렉토리들이 모두 비어져 있어야 한다. 별로 사용을 많이 하지 않음

os.mkdir('dir_path_to_make')
  • argument에 해당하는 directory을 생성
  • 단점은 dir_path_to_make 상에 있는 directory가 실제로 없는 경우, 생성이 안됨.
  • 경로순서 대로 디렉토리들을 차례로 만들어줘야 하는 단점이 있음.
  • 이미 있는 directory를 만들려고 하면 FileExistsError 발생.

실제로 쓰기 불편한 점이 많다보니
makedirs를 보다 많이 사용한다.


os.makedirs('dir_path_to_make`, exist_ok=True)
  • mkdir과 달리 지정한 경로 중간에 있는 디렉토리까지 없다면 다 생성해줌.
  • exist_okTrue로 지정할 경우, 이미 있는 디렉토리라도 FileExistsError가 발생하지 않음.

os.listdir('dir_path')
  • argument에 해당하는 directory에 속한 subdirectory와 file들을 item으로 가지는 list반환.

Unix shell 의 와일드 카드 등을 제공하는
glob 모듈의 glob 함수가 listdir보다 사용하기 쉽고 강력함.


os.link('original_file_path', 'link_file_path')
  • hard link lin_file_path를 생성. (hard link는 inode를 공유!)
  • hard link는 동기화가 이루어지며 그 자체로도 file이라고 할 수 있음 (적어도 Python의 os.path.isfile()함수 결과로는).

os.symlink('original_file_path', 'link_file_path')
  • soft link (=symbolic link) link_file_path를 생성.
  • Windows의 바로가기와 비슷하지만, 구현은 다음
  • windows에서는 "개발자모드"와 관리자 권한 등이 필요하며 잘 사용되지 않음.
  • hard link와 달리 os.path.isfile()로 체크시 False반환.

os.system('cmd_to_execute')
  • OS의 shell을 통해 cmd_to_execute를 수행시킨다.
  • 0이 반환되면 에러 없이 수행됨을 의미함.
반응형

'Python' 카테고리의 다른 글

[Python] atan2  (1) 2023.07.10
[Python] lambda expression and map, filter, reduce.  (0) 2023.07.07
[Python] binary file : write and read  (0) 2023.07.04
[Python] Text File : read and write  (0) 2023.07.04
[Python] file : open and close  (0) 2023.07.04