
mkdir로 디렉터리를 생성할 수 있으며 이미 존재하는 디렉터리이면 FileExistsError가 발생하고
하위 디렉터리와 함께 생성할 때, 경로에 존재하지 않는 디렉터리가 존재하면 FileNotFoundError가 발생합니다.
하지만 makedirs를 이용하면 하위 디렉터리와 함께 생성 시 존재하지 않으면 생성해 주고
이미 디렉터리가 존재한다면 exist_ok에 True를 전달하여 FileExistsError를 방지할 수 있습니다.
import os
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
os.mkdir(path=os.path.join(BASE_DIR, "test1"))
# print(os.mkdir(path=os.path.join(BASE_DIR, "test\\test1")))
os.makedirs(name=os.path.join(BASE_DIR, "test\\test1"), exist_ok=True)
rmdir로 디렉터리를 삭제할 수 있습니다.
하지만 디렉터리 내 파일과 같은 데이터가 존재한다면 디렉터리가 비어있지 않아서 OSError가 발생합니다.
shutil을 이용하여 하위 데이터도 모두 삭제할 수 있습니다.
import os
import shutil
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
os.makedirs(name=os.path.join(BASE_DIR, "test1"), exist_ok=True)
if os.path.exists(path=os.path.join(BASE_DIR, "test1")):
os.rmdir(path=os.path.join(BASE_DIR, "test1"))
os.makedirs(name=os.path.join(BASE_DIR, "test2"), exist_ok=True)
with open(file=os.path.join(BASE_DIR, "test2", "test.txt"), mode="w", encoding="utf8") as fp:
fp.write("Hello, World")
if os.path.exists(path=os.path.join(BASE_DIR, "test2")):
shutil.rmtree(path=os.path.join(BASE_DIR, "test2"))
파일의 MAC 시간, 크기, 권한 등의 정보를 확인할 수 있습니다. MAC 시간의 변화를 살펴 보기 위해 파일을 생성 후 3초 뒤에 데이터를 추가해 봅니다.
import os
import time
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
os.makedirs(name=os.path.join(BASE_DIR, "test1"), exist_ok=True)
time.sleep(3)
with open(file=os.path.join(BASE_DIR, "test1", "test.txt"), mode="w", encoding="utf8") as fp:
fp.write("Hello, World")
파일의 MAC 시간을 확인해 보면 약 ctime에서 3초 뒤로 mtime, atime이 설정되어 있는 것을 확인할 수 있습니다.
import os
import datetime
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
stat = os.stat(path=os.path.join(BASE_DIR, "test1"))
print(f"Modification time : {datetime.datetime.fromtimestamp(stat.st_mtime)}")
print(f"Access time : {datetime.datetime.fromtimestamp(stat.st_atime)}")
print(f"Metadata change / Create time : {datetime.datetime.fromtimestamp(stat.st_ctime)}")
mtime = os.path.getmtime(filename=os.path.join(BASE_DIR, "test1"))
atime = os.path.getatime(filename=os.path.join(BASE_DIR, "test1"))
ctime = os.path.getctime(filename=os.path.join(BASE_DIR, "test1"))
print(f"Modification time : {datetime.datetime.fromtimestamp(mtime)}")
print(f"Access time : {datetime.datetime.fromtimestamp(atime)}")
print(f"Metadata change / Create time : {datetime.datetime.fromtimestamp(ctime)}")
MAC 시간, 크기, 권한 등 종합적으로 확인 볼 수 있습니다.
| Attribute | Description |
|---|---|
| st_mode | file type adn permissions |
| st_ino | indoe number |
| st_dev | device id |
| st_uid | owner id |
| st_gid | group id |
| st_size | file size |
| st_mtime st_atime st_ctime | MAC Time |
import os
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
print(os.stat(path=os.path.join(BASE_DIR, "test1")))
실습을 위해 다음과 같은 디렉터리 구조를 만들어 봅니다.
C:\Users\admin\Desktop\python>tree . /f
디렉터리 PATH의 목록입니다.
볼륨 일련 번호가 00000076 8ACE:4F61입니다.
C:\USERS\ADMIN\DESKTOP\PYTHON
│ test.py
│
├─test1
│ ├─1-1
│ │ 1-1.txt
│ │
│ ├─1-2
│ │ 1-2.exe
│ │
│ └─1-3
│ 1-3.pdf
│
├─test2
│ ├─2-1
│ │ 2-1.txt
│ │
│ ├─2-2
│ │ 2-2.zip
│ │
│ └─2-3
│ 2-3.txt
│
└─test3
3-1.html
현재 디렉터리 안에 파일 및 디렉터리를 조회해 봅니다.
listdir, scandir, iterdir 모두 현재 디렉터리 내 파일 및 디렉터리에 대한 정보를 반환합니다.
import os
import pathlib # Python >= 3.4
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
listdirs = os.listdir(path=BASE_DIR)
for listdir in listdirs:
print(os.path.join(BASE_DIR, listdir), listdir, os.path.isdir(s=os.path.join(BASE_DIR, listdir)))
scandirs = os.scandir(path=BASE_DIR)
for scandir in scandirs:
print(scandir.path, scandir.name, scandir.is_dir())
path = pathlib.Path(BASE_DIR)
for iterdir in path.iterdir():
print(iterdir, iterdir.name, iterdir.is_dir())
실습을 위해 다음과 같은 디렉터리 구조를 만들어 봅니다.
C:\Users\admin\Desktop\python>tree . /f
디렉터리 PATH의 목록입니다.
볼륨 일련 번호가 00000076 8ACE:4F61입니다.
C:\USERS\ADMIN\DESKTOP\PYTHON
│ test.py
│
├─test1
│ ├─1-1
│ │ 1-1.txt
│ │
│ ├─1-2
│ │ 1-2.exe
│ │
│ └─1-3
│ 1-3.pdf
│
├─test2
│ ├─2-1
│ │ 2-1.txt
│ │
│ ├─2-2
│ │ 2-2.zip
│ │
│ └─2-3
│ 2-3.txt
│
└─test3
3-1.html
현재 디렉터리 내 파일 및 디렉터리뿐만 아니라 하위 디렉터리의 파일들도 조회해 볼 수 있습니다.
import os
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
for dirpath, dirnames, files in os.walk(top=BASE_DIR, topdown=True):
for file in files:
print(os.path.join(dirpath, file), file.startswith("1-"), file.endswith(".txt"), os.path.splitext(p=file))