Python에서 제공하는 File, Directory의 경로에 관련된 API를 알아보겠습니다.
현재 작업 폴더 경로
getcwd()
는 python 실행 파일의 부모 경로를 리턴합니다.
import os
print(os.getcwd())
Output:
/home/mjs/python-example/tests
작업 경로 변경
chdir()
은 현재 프로그램의 작업 경로를 변경할 수 있습니다.
변경 후, getcwd()
를 호출하면 변경된 dir이 리턴됩니다.
import os
os.chdir('/home/mjs/project')
print(os.getcwd())
Output:
/home/mjs/project
작업 경로의 파일 리스트 출력
아무 인자가 없이 listdir()
를 호출하면 작업 경로에 있는 파일 리스트를 출력합니다.
import os
print(os.getcwd())
print(os.listdir())
Output:
['directory.py', 'date_and_time.py', 'test_code.py', 'example.py', 'sleep_example.py']
특정 경로의 파일 리스트 출력
listdir()
의 인자로 path를 넘겨주면 그 path의 파일 리스트를 리턴합니다.
path는 상대경로나 절대경로 모두 가능합니다.
import os
print(os.listdir("./"))
Output:
['directory.py', 'date_and_time.py', 'test_code.py', 'example.py', 'sleep_example.py']
폴더 생성
mkdir()
는 현재 작업 경로에 인자로 전달된 이름으로 폴더를 생성합니다.
import os
os.mkdir('test_dir')
print(os.listdir())
Output:
['test_dir', 'example.py']
디렉토리 이름 변경
rename()
으로 폴더 이름을 변경할 수 있습니다. 첫번째 인자로 변경할 디렉토리 이름을, 두번째 인자로 변경하고 싶은 이름을 입력합니다.
import os
os.mkdir('test_dir')
print(os.listdir())
os.rename('test_dir', 'renamed_dir')
print(os.listdir())
Output:
['test_dir', 'example.py']
['example.py', 'renamed_dir']
디렉토리 삭제
rmdir()
은 인자로 전달되는 디렉토리를 삭제합니다.
import os
os.mkdir('test_dir')
print(os.listdir())
os.rmdir('test_dir')
print(os.listdir())
Output:
['test_dir', 'example.py']
['example.py']
rmdir()
은 비어있는 디렉토리만 삭제합니다. 디렉토리 안에 어떤 파일이 있다면 다음과 같은 에러와 함께 실패합니다.
import os
os.mkdir('test_dir')
os.mkdir('test_dir/test_dir2')
os.rmdir('test_dir')
Output:
Error
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
yield
File "/usr/lib/python3.6/unittest/case.py", line 605, in run
testMethod()
File "/home/mjs/python-example/tests/example.py", line 50, in test7
os.rmdir('test_dir')
OSError: [Errno 39] Directory not empty: 'test_dir'
디렉토리와 파일 모두 삭제
디렉토리와 그 안에 존재하는 모든 파일도 삭제하고 싶다면 shutil.rmtree()
를 사용하면 됩니다.
import shutil
import os
os.mkdir('test_dir')
os.mkdir('test_dir/test_dir2')
shutil.rmtree('test_dir')
상대 경로를 절대 경로로 변환
abspath()
는 인자로 전달된 상대경로를 절대 경로로 변환합니다.
import os
path = "./"
print(os.path.abspath(path))
Output:
/home/mjs/python-example/tests
Dir과 File 이름 분리
os.path.split()
는 인자로 전달된 Path에서 디렉토리 경로와 File 이름을 분리하여 Tuple로 리턴합니다.
import os
path = "/home/mjs/myproject/test.py"
paths = os.path.split(path)
print(paths)
Output:
('/home/mjs/myproject', 'test.py')
다음과 같이 dir과 file 변수에 바로 할당하도록 할 수도 있습니다.
dir, file = os.path.split(path)
print(dir)
print(file)
Output
/home/mjs/myproject
test.py
파일 경로 생성(Join)
join()
으로 Directory 경로와 파일 이름으로 path를 생성할 수 있습니다.
다음과 같이 dir과 file 이름을 인자로 전달합니다.
import os
path = os.path.join("/home/mjs/myproject", "test.py")
print(path)
Output:
/home/mjs/myproject/test.py
파일이 존재하는지 확인
exists()
로 파일 또는 디렉토리가 존재하는지 확인할 수 있습니다.
import os
if os.path.exists("/home/mjs"):
print("This dir exists")
Output:
This dir exists
디렉토리인지 확인
isdir()
으로 인자로 전달된 경로가 Directory인지 확인할 수 있습니다. 디렉토리가 아닌 파일이라면 False가 리턴됩니다.
import os
if os.path.isdir("/home/mjs"):
print("It's directory")
Output:
It's directory
파일인지 확인
isfile()
은 인자로 전달된 경로가 파일이라면 True를 리턴합니다. 디렉토리라면 False가 리턴됩니다.
if not os.path.isfile("/home/mjs"):
print("It's not file")
if os.path.isfile("/home/mjs/test.py"):
print("It's file")
Output:
It's not file
It's file
Recommended Posts:
- Python - dict 정렬 (Key, Value로 sorting)
- Python - String을 bytes로 변경하는 방법
- Python - bytes를 String으로 변환하는 방법
- Python - 리스트에서 첫번째, 마지막 요소 가져오는 방법
- Python - 문자열에서 특정 단어 추출
- Python - float을 int로 변경하는 방법
- Python - 특정 문자열로 시작하는 문자열 찾기
- Python - dictionary의 중복 제거 방법
- Python - 리스트가 비어있는지 확인
- Python - 문자열 뒤집기, 문자열 거꾸로 출력
- Python - 현재 날짜, 시간 가져오는 방법
- Python - 두개의 리스트 하나로 합치기
- Python - 리스트 크기(size) 구하기