<aside> 💡 파일과 폴더를 생성/수정/삭제하는 기본적인 방식입니다.

</aside>

import os

file_path = "first_file.txt"

# 파일 존재 여부 확인
file_exists = os.path.exists(file_path)

pass
# 파일 열기
with open(file_path, 'r') as file:
    file_content = file.read()
print(f"파일 내용:\\n{file_content}")

<aside> ❓ 파이썬의 open 함수에 대해 매개변수를 포함하여 자세히 알려줘.

</aside>

# 보다 안전한 코드
try:
    with open(file_path, 'r', encoding="UTF-8") as file:
        file_content = file.read()
    print(f"파일 내용:\\n{file_content}")
except Exception as e:
    print(f"⚠️ 파일 읽기 중 오류 발생: {e}")
# 파일 쓰기
try:
    with open(file_path, 'w') as file:
        file.write('Hello, world!')
except Exception as e:
    print(f"⚠️ 파일 쓰기 중 오류 발생: {e}")
# 내용 추가하기
try:
    with open(file_path, 'a', encoding="UTF-8") as file:
        for fruit in ["사과", "배", "귤"]:
            file.write(f"\\n{fruit} 사세요.")
except Exception as e:
    print(f"⚠️ 파일 내용 추가 중 오류 발생: {e}")