<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}")
with : 파일을 열 때 사용하며 사용 후 파일을 자동으로 닫아줌open : 파일을 여는데 사용되는 함수
r (기본) : 읽기w : 쓰기a : 추가+ : 읽기&쓰기<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}")
encoding="UTF-8" 인자 추가할 것!