Skip to content
조회 수 2051 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

파이썬 os 모듈, 파일(file)과 디렉토리(directory)활용

 

 

. os 모듈의 다양한 함수

os 모듈은 내 컴퓨터의 디렉터리(폴더)나 경로, 파일 등을 활용하게 도와주는 모듈로 활용빈도가 굉장히 높다.
이 모듈이 제공하는 다양한 함수들에 대해 알아보자

1-1. os.getcwd() : 현재 작업 디렉토리 확인

os.getcwd()
[Output]
'C:\\Users\\User\\Desktop\\'

1-2. os.chdir() : 현재 작업 디렉토리 변경

os.chdir("D:/")
os.getcwd()
[Otuput]
'D:\\'

1-3. os.listdir() : 입력 경로 내의 모든 파일과 폴더명 리스트 반환

os.listdir("C:/Users/User/Desktop")
[Output]
['python_practice.py',
 '연구노트.hwp'
 '개인자료',
 '새 폴더',
 '공유자료',
 '데이터설명서모음',
 '크기비교 수정']

폴더는 폴더명, 파일은 확장자명까지 알려준다.

1-4. os.mkdir() : 폴더 생성

os.mkdir("C:/Users/User/Desktop/test")
os.listdir("C:/Users/User/Desktop/")
[Output]
['python_practice.py',
 '연구노트.hwp'
 '개인자료',
 '새 폴더',
 '공유자료',
 '데이터설명서모음',
 '크기비교 수정',
 'test']

입력 경로의 마지막의 디렉토리 명으로 폴더를 생성한다.
이미 있는 파일명일 경우, 에러가 발생한다.

os.mkdir("C:/Users/User/Desktop/test")
[Output]
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-29-703c0a2ae4a0> in <module>
----> 1 os.mkdir("C:/Users/User/Desktop/tes1t")
FileExistsError: [WinError 183] 파일이 이미 있으므로 만들 수 없습니다: 'C:/Users/User/Desktop/tes1t'

1-5. os.makedirs() : 모든 하위 폴더 생성

경로의 제일 마지막에 적힌 폴더 하나만 생성하는 os.mkdir()과 달리 os.makedirs()함수는 경로의 모든폴더를 만들어 준다.

os.makedirs("C:/Users/User/Desktop/test/a/b")

실제로 확인해보면, C:/Users/User/Desktop/test/a/b이 생겨있다.

print(os.listdir("C:/Users/User/Desktop/tes1t/a/b"))
os.remove("C:/Users/User/Desktop/tes1t/a/b/test.txt")
print(os.listdir("C:/Users/User/Desktop/tes1t/a/b"))
[Output]
['test.txt']
[]

os.unlink()함수도 똑같이 동작한다.

1-7. os.rmdir() : 빈 폴더 삭제(가장 하위 폴더만)

빈 폴더만을 삭제해주며, 비어있지 않을 경우 에러 발생

os.rmdir("C:/Users/User/Desktop/test/a/b")
[Output]
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-41-d718dffe3d52> in <module>
----> 1 os.rmdir("C:/Users/User/Desktop/test/a/b")

OSError: [WinError 145] 디렉터리가 비어 있지 않습니다: 'C:/Users/User/Desktop/test/a/b'

1-8. os.walk() : 경로, 폴더명, 파일명 모두 반환

os.walk()함수는 입력한 경로부터 그 경로 내의 모든 하위 디렉토리까지 하나하나 찾아다니며, 각각의 경로와 폴더명, 파일명들을 반환해 주는 함수이다.
generator로 반환해 주기 떄문에 for문이나 반복가능한(iterable) 함수 읽어야 한다.

for path, direct, files in os.walk("c:/Users/User/Desktop"):
    print(path)
    print(direct)
    print(files)
[Output]
c:/Users/User/Desktop
['code_study', 'test']
['test1.txt', 'test2.txt', 'test3.txt', 'testtest.csv', '이슈 메모.hwp']
c:/Users/User/Desktop\code_study
['.ipynb_checkpoints', 'practice', 'review', '가져온자료']
['chunck.R', 'python_code_url.hwp']

(너무많아서 결과를 살짝 수정하긴 했다.)

결과를 보듯이 (해당경로, 폴더명리스트, 파일명리스트), (다음 경로, 폴더명리스트, 파일명리스트) 순으로 계속 탐색을 해준다.
현재는 print만 했지만 가장 쉽고 폭넓게 탐색이 가능한 함수로 매우 유용하게 사용된다.

2. os.path 모듈의 다양한 함수

os.path 모듈은 파일 또는 폴더 명이나, 확장자, 존재유무 등을 알아볼 수 있는 모듈이다.

2-1. os.path.isdir() : 폴더 유무 판단

입력된 경로가 폴더인지 아닌지 판별해준다.

os.path.isdir("C:/Users/User/Desktop/test")
[Output]
True

폴더가 없는 경우에도 False를 반환

os.path.isdir("C:/Users/User/Desktop/nono")
[Output]
False

2-2. os.path.isfile() : 파일 유무 판단

마찬가지로 이번엔 파일인지 아닌지를 판별하고,
파일이면 True, 아니면 False, 없어도 False를 반환한다.

os.path.isfile("C:/Users/User/Desktop/test/test.txt")
[Output]
True

2-3. os.path.exists() : 파일이나 폴더의 존재여부 판단

파일,폴더이면 True, 해당 파일,폴더가 없을때 False

os.path.exists("C:/Users/User/Desktop/test/test.txt")
[Output]
True
os.path.exists("C:/Users/User/Desktop/test/")
[Output]
True

2-4. os.path.getsize() : 파일의 크기(size) 반환

os.path.getsize("C:/Users/User/Desktop/test/test.txt")
[Output]
856

단위는 바이트이다.

2-5. os.path.split() os.path.splitext() : 경로와 파일 분리

이 두 함수는 실제 파일 또는 폴더의 존재여부와는 상관없이 텍스트로 분리해준다.
전자는 맨 하위에 위치한 파일 또는 폴더명 분리

os.path.split("C:/Users/User/Desktop/test/test.txt")
[Output]
('C:/Users/User/Desktop/test', 'test.txt')

확장자 분리

os.path.splitext("C:/Users/User/Desktop/test/test.txt")
[Output]
('C:/Users/User/Desktop/test/test', '.txt')

2-6. os.path.join() : 파일명과 경로를 합치기

path = "C:/User/Desktop/test"
filename = "test.txt"
os.path.join(path, filename)
[Output]
'C:/User/Desktop/test\\test.txt'

그냥 슬래쉬(/ 또는 \)로 결합해주는 역할을 한다.

2-7. os.path.dirname()os.path.basename()

dirname()함수는 입력 경로의 폴더경로까지 꺼내주고, basename()함수는 파일이름만 꺼내주는 함수이다.
앞의 os.path.split()함수의 튜플을 꺼낸 것과 동일하다.

os.path.dirname("C:/Users/User/Desktop/test/test.txt")
[Output]
'C:/Users/User/Desktop/test'
os.path.basename("C:/Users/User/Desktop/test/test.txt")
[Output]
'test.txt'

ref

참고블로그
os모듈에 대한 정리를 굉장히 잘 해놓으셔서, 공부하고 따해볼겸 참고해서 작성하게 되었습니다. 작성자분 감사드립니다.

로그인 후 댓글쓰기가 가능합니다.

?

List of Articles
번호 분류 제목 날짜 조회 수
233 AVR 5V로 정전압 출력하기 2013.06.28 11838
232 회로도전자부품 AC to DC Converter file 2013.09.09 18150
231 회로도전자부품 AC 모터 정역회전 file 2018.11.06 12384
230 회로도전자부품 AM FM one transistor am transmitter & Reciver 1 2014.03.04 8962
229 회로도전자부품 AM/FM 라디오 구조(회로도 설명) 1 2014.04.02 25424
228 회로도전자부품 Arduino Frequency Counter Library file 2014.01.20 30873
227 AVR ARDUINO 명령어 모음 3 2012.07.24 22870
226 AVR Arduino 특정시간 제어와 릴레이 다루기 2019.06.13 11957
225 AVR arduino에서 5V Relay Module 을 이용하여 220V 교류 제어 2 2012.08.03 6583
224 AVR AVR의 기초 3 2012.07.18 6504
223 회로도전자부품 BN39-01154W 단자구성도 file 2013.12.31 12863
222 회로도전자부품 BOOST LIST file 2013.10.12 16321
221 회로도전자부품 BUILD FM TRANSMITTER CIRCUIT (제작완료) file 2014.04.15 4239
220 회로도전자부품 C1815 트랜지스터 데이터시트 file 2014.01.11 14426
219 회로도전자부품 CCTV file 2015.07.03 1180
218 회로도전자부품 CCTV 견적서 file 2015.12.14 1224
217 회로도전자부품 CCTV 설치시 구성품/필수또는선택사항/주의사항/참고사항 file 2015.12.15 1875
216 AVR CD-ROM 모터 정보 모으기 2 file 2012.08.20 8855
215 회로도전자부품 CDS저항으로 야간취침등 만들기 file 2014.03.17 4633
214 회로도전자부품 CDS회로(LED 켜기) file 2014.02.10 8201
Board Pagination Prev 1 2 3 4 5 ... 13 Next
/ 13

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소