
mode가 w 이면 파일이 이미 존재하여도 새롭게 작성됩니다.
mode에 b가 함께 전달되면 바이너리 형식으로 취급됩니다.
import os
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
with open(file=os.path.join(BASE_DIR, "test1.txt"), mode="w", encoding="utf8") as fp:
fp.write("Hello, World\n")
fp.write("반갑습니다.\n")
with open(file=os.path.join(BASE_DIR, "test2.txt"), mode="wb") as fp:
fp.write(b"Hello, World\n")
fp.write("반갑습니다.\n".encode())
mode가 r 이면 파일이 이미 존재하고 있어야 합니다. 존재하지 않다면 FileNotFoundError가 발생합니다.
mode에 b가 함께 전달되면 바이너리 형식으로 취급됩니다.
readlines는 개행이 이루어지는 곳에서 나뉘어 리스트형으로 반환되고
readline은 단 한 줄만 읽고
read는 파일 전체를 읽습니다.
import os
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
with open(file=os.path.join(BASE_DIR, "test1.txt"), mode="r", encoding="utf8") as fp:
print(fp.readlines()) # ['Hello, World\n', '반갑습니다.\n']
with open(file=os.path.join(BASE_DIR, "test1.txt"), mode="r", encoding="utf8") as fp:
print(fp.readline()) # Hello, World
with open(file=os.path.join(BASE_DIR, "test2.txt"), mode="rb") as fp:
print(fp.read().decode()) # Hello, World\n반갑습니다.\n
mode가 a 이면 파일이 이미 존재한다면 이어 쓰기가 되며 파일이 존재하지 않다면 mode가 w와 같이 작동합니다.
mode에 b가 함께 전달되면 바이너리 형식으로 취급됩니다.
import os
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
with open(file=os.path.join(BASE_DIR, "test1.txt"), mode="a", encoding="utf8") as fp:
fp.write("Append data\n")
with open(file=os.path.join(BASE_DIR, "test1.txt"), mode="r", encoding="utf8") as fp:
print(fp.read()) # Hello, World\n반갑습니다.\nAppend data\n
with open(file=os.path.join(BASE_DIR, "test2.txt"), mode="ab") as fp:
fp.write(b"Append data\n")
with open(file=os.path.join(BASE_DIR, "test2.txt"), mode="rb") as fp:
print(fp.read().decode()) # Hello, World\n반갑습니다.\nAppend data\n
with open(file=os.path.join(BASE_DIR, "test3.txt"), mode="a", encoding="utf8") as fp:
fp.write("Create New File\n")
with open(file=os.path.join(BASE_DIR, "test3.txt"), mode="r", encoding="utf8") as fp:
print(fp.read()) # Create New File\n
경로에 파일이 존재한다면 삭제합니다.
import os
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
if os.path.exists(path=os.path.join(BASE_DIR, "test1.txt")):
os.remove(path=os.path.join(BASE_DIR, "test1.txt"))
if os.path.exists(path=os.path.join(BASE_DIR, "test2.txt")):
os.remove(path=os.path.join(BASE_DIR, "test2.txt"))
if os.path.exists(path=os.path.join(BASE_DIR, "test3.txt")):
os.remove(path=os.path.join(BASE_DIR, "test3.txt"))
파일의 MAC 시간, 크기, 권한 등의 정보를 확인할 수 있습니다.
MAC 시간의 변화를 살펴 보기 위해 파일 생성 후 3초 뒤에 데이터를 추가해 봅니다.
import os
import time
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
with open(file=os.path.join(BASE_DIR, "test1.txt"), mode="w", encoding="utf8") as fp:
fp.write("Hello, World\n")
fp.write("반갑습니다.\n")
time.sleep(3)
with open(file=os.path.join(BASE_DIR, "test1.txt"), mode="a", encoding="utf8") as fp:
fp.write("Append Data\n")
파일의 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.txt"))
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.txt"))
atime = os.path.getatime(filename=os.path.join(BASE_DIR, "test1.txt"))
ctime = os.path.getctime(filename=os.path.join(BASE_DIR, "test1.txt"))
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)}")
파일의 크기를 구해볼 수 있습니다. 단위는 Byte입니다.
import os
BASE_DIR = "C:\\Users\\admin\\Desktop\\python"
size = os.path.getsize(filename=os.path.join(BASE_DIR, "test1.txt"))
print(f"size : {size} Bytes")
stat = os.stat(path=os.path.join(BASE_DIR, "test1.txt"))
print(f"size : {stat.st_size} Bytes")
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.txt")))