파이썬
Python 파일 입출력과 예외 처리
lightmoo
2024. 6. 12. 12:51
반응형
Python 파일 입출력과 예외 처리
소개
이번 강좌에서는 Python에서 파일을 읽고 쓰는 방법과 예외를 처리하는 방법에 대해 학습합니다. 파일 입출력과 예외 처리는 Python 프로그래밍에서 중요한 부분을 차지하며, 데이터를 효과적으로 관리하고 오류를 처리하는 데 필수적입니다.
1. 파일 입출력
파일 열기와 닫기
# 파일 열기
file = open("example.txt", "w")
file.write("Hello, Python!")
file.close()
# with 문을 사용한 파일 열기
with open("example.txt", "w") as file:
file.write("Hello, Python with 'with' statement!")
파일 읽기
# 전체 파일 읽기
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 한 줄씩 읽기
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
파일 쓰기
# 새로운 내용 추가하기 (append 모드)
with open("example.txt", "a") as file:
file.write("\nAppending new content.")
2. 예외 처리
기본 예외 처리
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
다양한 예외 처리
try:
file = open("non_existent_file.txt", "r")
except FileNotFoundError:
print("File not found!")
except Exception as e:
print(f"An error occurred: {e}")
예외 처리와 else, finally
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result is {result}")
finally:
print("This block is always executed")
마무리
이번 강좌에서는 Python에서 파일을 읽고 쓰는 방법과 예외를 처리하는 방법에 대해 학습했습니다. 파일 입출력과 예외 처리는 실무에서 매우 중요하며, 연습을 통해 확실히 이해하고 활용할 수 있도록 노력하세요.