안녕하세요. SQLER의 코난 김대우입니다.
이번 강좌에서는, Python 중급 강좌 - 6. 파일시스템(File system) 관리를 진행토록 하겠습니다.
SQLER에서 진행되는 전체 Python / 머신러닝 강좌 목록
코드를 실행하기 위해서는, vscode에서 새로운 파일을 만들고 실행하시면 됩니다.
예를 들어, 6_filesystem.py를 생성하고 코드를 실행합니다.
Python 중급 강좌 - 6. 파일시스템(File system) 관리
Python의 pathlib은 파일 시스템의 파일 및 디렉토리에 액세스하기 위한 여러 명령 및 클래스를 제공합니다.
os.path 도 사용되나, 3.6 버전 이상의 Python에서 pathlib을 사용 하실 것을 권장해드립니다.
Python으로 path 관리 작업
특히, 어플리케이션을 개발하면서, 파일의 full path나 해당 개체가 file인지 directory인지 체크 해야할 경우가 있습니다.
이러한 다양한 작업을 pathlib을 이용해 수행 가능합니다.
# Python 3.6 이상 필요 # 라이브러리 참조 from pathlib import Path # 현재 작업 디렉토리 체크 cwd = Path.cwd() print('\nCurrent working directory:\n' + str(cwd)) # 전체 경로명을 경로(path)와 파일명을 join해 생성 / 출력 new_file = Path.joinpath(cwd, 'new_file.txt') print('\nFull path:\n' + str(new_file)) # 파일이 존재하는지 체크 print('\nDoes that file exist? ' + str(new_file.exists()) + '\n')
이러한 일반적인 path 작업을 Python에서 진행할 수 있습니다.
Python에서 디렉토리(directory) 작업
from pathlib import Path cwd = Path.cwd() # 상위 디렉토리 참조 parent = cwd.parent # 디렉토리인지 체크 print('\nIs this a directory? ' + str(parent.is_dir())) # 파일인지 체크 print('\nIs this a file? ' + str(parent.is_file())) # 하위 디렉토리 목록 리스트 print('\n-----directory contents-----') for child in parent.iterdir(): if child.is_dir(): print(child)
이렇게 디렉토리 관련 작업을 Python에서 처리 가능합니다.
Python에서 파일작업
from pathlib import Path cwd = Path.cwd() demo_file = Path(Path.joinpath(cwd, 'demo.txt')) # 파일명 가져오기 print('\nfile name: ' + demo_file.name) # 파일의 확장자 가져오기 print('\nfile suffix: ' + demo_file.suffix) # 폴더명 가져오기 print('\nfile folder: ' + demo_file.parent.name) # 크기 가져오기 print('\nfile size: ' + str(demo_file.stat().st_size) + '\n')
이렇게 파일 관련 작업을 Python에서 수행 가능합니다.
추가적으로 자주 사용하게 되는 여러 파일&디렉토리 작업들을 정리합니다.
특정 디렉토리의 모든 파일 목록을 리스트로 가져오는 방법
# listdir을 이용하는 방법 from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] # 또는 glob을 이용한 방법 import glob print(glob.glob("/home/adam/*.txt"))
이 외에도 여러 방법을 아래 링크에서 확인 가능합니다.
참고링크 : python - How do I list all files of a directory? - Stack Overflow
그럼 다음 강좌에서 뵐게요.
참고자료
개발자 커뮤니티 SQLER.com - Python 무료 강좌 - 기초, 중급, 머신러닝
python - How do I list all files of a directory? - Stack Overflow