OS 모듈
[ 한 줄 정의 ]
Operating System의 약자. 운영체제에서 사용할 수 있는 기능을 파이썬에서 쓸 수 있게 해주는 파이썬 기본 모듈
[ 기능 ]
함수 | 기능 |
os.listdir() 함수 | 폴더 안에 있는 파일 리스트를 만들어 줌 |
os.path.join() 함수 | 경로명과 파일명을 붙여서 파일 접속경로를 만들어 줌 |
os.path.splitext() 함수 | (점) 을 기준으로 텍스트를 나눠주는 함수. 파일명.확장자 |
os.walk() 함수 | 해당 폴더의 하위 폴더(dir)를 모두 반환 |
1. 폴더 안에 있는 파일 리스트를 만들어 줌
2. 경로명과 파일명을 붙여서 파일 접속경로를 만들어 줌
3. 전체 파일 접속 경로를 폴더/파일명/확장자 구분으로 잘라 줌
4. 해당 폴더의 하위 폴더 전체에 대한 파일 리스트 반환
[ python documentation 공식문서]
https://docs.python.org/3/library/os.html
os — Miscellaneous operating system interfaces — Python 3.10.3 documentation
os — Miscellaneous operating system interfaces Source code: Lib/os.py This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.
docs.python.org
1. os.listdir() 함수
: 폴더 안에 있는 파일 리스트를 만들어 줌
import os
os.listdir()
>>> ['.cache',
'.conda',
'.ipynb_checkpoints',
'.ipython',
'.jupyter',
'.keras',
'.matplotlib',
'.streamlit',
'3D Objects',
'Anaconda3']
2. os.path.join() 함수
: 경로명과 파일명을 붙여서 파일 접속경로를 만들어 줌
import os
dirname = "C:\\"
filenames = os.listdir(dirname)
for filename in filenames:
full_filename = os.path.join(dirname, filename)
print(full_filename)
>>>C:\$Recycle.Bin
C:\$WinREAgent
C:\bootmgr
C:\BOOTNXT
C:\chromedriver.exe
C:\Config.Msi
C:\DecodeView
C:\DOCUMENTS
3. os.path.splitext() 함수
: .(점) 을 기준으로 텍스트를 나눠주는 함수. "파일명.확장자" 에서 파일명과 확장자 둘로 나눠줌.
이후 인덱싱 [-1]을 통해 확장자를 추출 가능
dirname = 'C:\\'
filenames = os.listdir(dirname)
for filename in filenames:
full_filename = os.path.join(dirname, filename)
ext = os.path.splitext(full_filename)[-1]
if ext == '.txt':
print(full_filename)
>>> C:\IsUrlMoniker.txt
C:\nsispromotion_log.txt
4. os.walk() 함수
: 해당 폴더의 하위 폴더(dir)를 모두 확인해주는 함수
for (path, dir, files) in os.walk("c:/"):
print(path, dir, files)
>>> c:/
['$Recycle.Bin', '$WinREAgent', 'Config.Msi', 'DecodeView', 'DOCUMENTS', 'Documents and Settings]
['bootmgr', 'BOOTNXT', 'chromedriver.exe', 'DumpStack.log', 'DumpStack.log.tmp', 'end', 'ezCertIssuerCore.log']
5. OS 모듈 함수 종합 사용 예제
import os
for (path, dir, files) in os.walk("c:/"):
for filename in files:
ext = os.path.splitext(filename)[-1]
if ext == '.py':
print("%s/%s" % (path, filename))