pytho에는 파일을 다루기 쉽도록 도와주는 함수들이 많이 있다. 이번 글에서는 내가 파일을 다루는 프로그램을 짜면서 유용하게 썼던 모듈과 그 함수들을 소개해보고자 한다.
os module
os.path.exists
os.path.exists(file_path) : file_path 경로의 파일이 있는지 확인해준다.
if not os.path.exists(file_path):
print ('Error: %s does not exist' %(file_path))
os.makedirs
os.makedirs(dir_path) : dir_path 에 디렉토리를 만들어준다.
try:
if not os.path.exists(dir_path):
os.makedirs(dir_path)
except OSError:
print('Error: Creating directory. ' + dir_path)
os.listdir
os.listdir(dir_path) : dir_path 디렉토리에 있는 파일 리스트를 가져와준다.
file_list = os.listdir(src)
for file in file_list:
~
os.path.isdir
os.path.isdir(path) : path 에 해당하는 것이 디렉토리인지 확인해준다.
os.path.splitext
os.path.splitext(file_path) : file_path 를 [파일 이름, 확장자]로 분리해준다.
os.path.getsize
os.path.getsize(path) : path 의 크기를 알려준다.
shutil module
copy
shutil.copy(src, des) : src를 des로 복사한다. (메타 정보 미포함)
copy2
shutil.copy2(src, des) : src를 des로 복사한다. (메타 정보 포함)