OS module: operating system(운영체제)와 상호작용을 위한 다양한 기능을 제공하는 built-in module이다.
os.path 모듈
- ex_exist= os.path.exists('path_file')
- 'path_file'이 실제로 존재하는 파일 또는 디렉토리인 경우 True를 반환. 아닌 경우 False.
- ex_file=os.path.isfile('path_file')
- 'path_file'이 file인 경우 True를 반환. 아닌 경우 False.
- ex_dir=os.path.isdir('path_dir')
- 'path_file'이 directory인 경우 True를 반환. 아닌 경우 False.
- ex_path=os.path.join('path0', 'path1', 'path2')
- argument로 넘어온 문자열들을 순서대로 붙여서 하나의 path를 만들어냄.
- 여러 경로 요소를 하나의 경로로 결합하는데 사용
import os
base_path='C:'
folder1='Users'
folder2='danbe'
folder3='Documents'
file_name='exapmle.txt'
full_path=os.path.join(base_path,folder1,folder2,folder3,file_name)
print(full_path)
#출력값
C:Users\danbe\Documents\exapmle.txt #윈도우 기
- ex_split=os.path.split('/home/danbe/lecture')
- argument로 주어진 path를 2개로 나누어줌.
- 위의 예에서 'lecture'은 directory일 수도 file일 수도 있음.
- 위 예의 결과: '/home/danbe', 'lecture'
- ex_link=os.path.islink('path_link')
- argument로 넘어온 path가 symbolic link인지 여부를 반환.
- hard link인 경우 False.
- ex_real=os.path.realpath('path_link')
- symbolic link 파일의 원본 위치를 반환
- ex_abs=os.path.abspath('path_abs')
- absolute path를 반환해줌.
- ex_dir=os.path.dirname('path_dir')
- argument의 path를 포함하는 directory의 path를 반환
- ex_base=os.path.basename('/path0/path1/path.txt')
- argument로 주어진 경로 중 말단의 이름을 반환.
import os
base_path='C:'
folder1='Users'
folder2='danbe'
folder3='Documents'
file_name='exapmle.txt'
full_path=os.path.join(base_path,folder1,folder2,folder3,file_name)
print(full_path)
base_name=os.path.basename(full_path)
print(base_name)
#출력값
C:Users\danbe\Documents\exapmle.txt
exapmle.txt #말단 이름 출력
exapmle.txt #말단 이름 출력
- ex_size=os.path.getsize('path_targetfile')
- 파일의 크기를 반환.
with open('target_file.txt', 'w') as f:
f.write('this is a sample file with some text datas.')
import os
file_path='target_file.txt'
file_size=os.path.getsize(file_path)
print(f'The size of {file_path} is: {file_size} bytes')
#출력값
The size of target_file.txt is: 43 bytesos module
- 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)
- 파일의 권한을 변경하는 함수
- '0o400'은 파일의 권한을 나타내는 숫자.8진수(base-8)
- 4: 읽기권한
- 0: 쓰기권한
- 0: 실행권한
- '400'은 읽기만 가능한 파일임.
- 위의 예는 'target_file_path'를 읽기만 가능한 파일로 변경하는 것임.
- os.remove('file_path_to_del')
- argument에 해당하는 file을 삭제
- os.rmdir('dir_path_to_del')
- argument에 해당하는 directory를 삭제
- directory가 존재하지 않거나, 비어있는 directory가 아닌 경우, FileNotFoundError를 발생시킴.
- 'shutil.rmtree()' 동일하게 사용 가능. 더 많이 사용함.
- os.mkdir('dir_path_to_make')
- argument에 해당하는 directory를 생성
- 경로 순서대로 directory를 차례로 만들어줘야하는 단점이 있음.
- 이미 있는 directory를 만드려고 할 시 FileExistsError 발생.
- os.makedirs('dir_path_to_make', exist_ok=True) 도 동일
- mkdir과 달리 지정한 경로 중간에 있는 디렉토리까지 없다면 다 생성해줌.
- exist_ok=True로 지정할 시, 이미 있는 디렉토리라도 FileExistsError가 발생하지 않음.
- os.link('original_file_path', 'link_file_path')
- hard link link_file_path를 생성. (hard link는 incode를 공유)
- hard link는 동기화가 이루어지며 그 자체로도 file이라고 할 수 있음
- os.symlink('original_file_path', 'link_file_path')
- soft link(=symbolic link) 'link_file_path' 생성
- hard link와 달리, os.path.isfile()로 체크 시 False반환.
- os.system('cmd_to_execute')
- os의 shell을 통해 'cmd_to_execute'를 수행시킨다.
- 0이 반환되면 에러 없이 수행됨을 의미함.
'컴퓨터프로그래밍' 카테고리의 다른 글
리눅스 명령어 (2) | 2024.06.04 |
---|---|
Path module (2) | 2024.06.03 |
File (2) | 2024.06.03 |
Iterator, Generator (0) | 2024.06.01 |
Comprehension (0) | 2024.05.31 |