[Python] os 모듈을 사용한 파일(디렉토리) 처리 총정리: 경로 확인, 경로 변경, 파일 이름 변경

오도원공육사·2021년 10월 13일
0

파이썬

목록 보기
6/11

참고.

os.path - Common pathname manipulations - Python 3.10.0 documentation

1. 현재 경로 확인

import os

# 현재 경로 조회. 작업 디렉토리 기준
print(os.getcwd()) 

# 현재 파일의 디렉토리 경로. 작업 파일 기준
print(os.path.dirname(os.path.realpath(__file__)))

2. 디렉토리 변경

import os

os.chdir("../") # 부모 디렉토리로 이동

3. 현재 폴더의 디렉토리 및 파일 리스트 확인

import os

files = os.listdir() # os.listdif(os.getcwd())와 동일

4. 파일명 제외하고 경로만 가져오기

import os

dirname = os.path.dirname("filepath")

5. 경로 제외하고 파일명만 가져오기

import os

filename = os.path.basename("filepath")

6. 파일/디렉토리 여부 확인

import os

# 해당 경로가 파일인지 확인
# 파일이면 True, 아니면 False 반환
is_file = os.path.isfile("inputpath")

# 해당 경로가 디렉토리인지 확인
# 디렉토리이면 True, 아니면 False 반환
is_dir = os.path.isdir("inputpath")

7. 디렉토리와 파일명 분리

import os

dirpath, filename = os.path.split("C:/Users/Python/Python39/python.exe")
print(dirpath) # C:/Users/Python/Python39
print(filename) # python.exe

8. 파일/디렉토리 존재 유무 확인

import os

exist = os.path.exists("inputpath") # 파일 또는 디렉토리 존재 유무 체크

9. 파일 크기 체크

import os

size = os.path.getsize("filepath")

10. 파일 또는 경로를 합치는 방법

import os

os.path.join("C:/Users/Python/Python39", "python.exe")
# C:/Users/Python/Python39/python.exe

11. 파일명과 확장자를 분리하는 방법

import os

name, ext = os.path.splitext("python.exe")
print(name) # python
print(ext) # .exe

12. 파일명을 변경하는 방법

import os

file_list = os.listdir("C:/Users/Python/Python39")
# 현재 파일이 ["test1.txt", "test2.txt", "test3.txt"]가 있다고 가정

os.renames("C:/Users/Python/Python39/test1.txt", "C:/Users/Python/Python39/good.txt")

print(os.listdir("C:/Users/Python/Python39"))
# ["good.txt", "test2.txt", "test3.txt"]

13. 현재 파일의 이름과 경로

import os

# 현재 파일의 이름
print(__file__)

# 현재 파일 실제 경로
print(os.path.realpath(__file__))

# 현재 파일 절대 경로
print(os.path.abspath(__file__))
profile
잘 먹고 잘살기

0개의 댓글