본문 바로가기

Programming/Python

os모듈 함수

파일의 경로상에서 디렉터리를 구분할때 

Windows 환경에서는 역슬래시(\)를 사용

Unix/Linux에서는 슬래시(/)를 사용

파이썬에서 문자열 리터럴을 표기하는 경우 역슬래시를 사용하기 위해서는 이스케이프 처리를 위해 역슬래시를 두 번 연속 사용해야 합니다.

 

os 모듈 : 내 컴퓨터의 Directory(폴더)나 경로, 파일 등을 활용하게 도와주는 모듈

 

1. 현재 작업 디렉토리 확인

import os
os.getcwd()

 

2. 현재 작업 디렉토리 변경

os.chdir("D:/")

# 변경된 작업 디렉토리 확인
os.getcwd()

 

3. 입력 경로 내의 모든 파일, 폴더 이름 리스트로 반환

- 파일은 확장자명까지 표시

os.listdir("C:/Users/User/Desktop")

 

4. 폴더 생성

os.mkdir("C:/Users/User/Desktop/test")

# 생성한 폴더 확인
os.listdir("C:/Users/User/Desktop/")

 

5. 경로로 표시한 모든 폴더 생성

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

 

6. 파일 삭제

# 파일 확인
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"))

 

7. 빈 폴더 확인하고 삭제

- 비어있지 않으면 오류 발생

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

 

8. 경로, 폴더명, 파일명 모두 반환

for path, direct, files in os.walk("c:/Users/User/Desktop"):
    print(path)
    print(direct)
    print(files)

 

9. 폴더 여부 확인

os.path.isdir("C:/Users/User/Desktop/test")
# True or False

 

10. 파일 여부 확인

os.path.isfile("C:/Users/User/Desktop/test/test.txt")
# True or False

 

11. 폴더나 파일 유무 확인

os.path.exists("C:/Users/User/Desktop/test/test.txt")
# True or False

 

12. 파일 크기(size) 확인

os.path.getsize("C:/Users/User/Desktop/test/test.txt")

 

13. 경로, 파일 확인

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')

 

14. 파일 이름과 경로 합치기

path = "C:/User/Desktop/test"
filename = "test.txt"
os.path.join(path, filename)

# 'C:/User/Desktop/test\\test.txt'

 

15. 상단 폴더까지 경로 분리

os.path.dirname("C:/Users/User/Desktop/test/test.txt")
# 'C:/Users/User/Desktop/test'

 

16. 파일이름 분리

os.path.basename("C:/Users/User/Desktop/test/test.txt")
# 'test.txt'

'Programming > Python' 카테고리의 다른 글

튜플  (0) 2020.09.15
입력값이 몇 개가 될지 모를 때(*args)  (0) 2020.09.15
영화평점 분석하기  (0) 2020.03.09
Pandas  (0) 2020.03.09
Numpy  (0) 2020.03.09