Skip to Content
💻 코리아IT아카데미 신촌 - 프로그래밍 학습 자료
Python 프로그래밍Unit 9: 파일 다루기Topic 1: 텍스트 파일 읽기

Topic 1: 텍스트 파일 읽기 📖

🎯 학습 목표

파이썬으로 텍스트 파일을 읽는 다양한 방법을 배워요!

  • 파일 열고 닫기의 기본
  • 파일 전체 읽기와 한 줄씩 읽기
  • with 문으로 안전하게 파일 다루기

📁 파일이란?

파일은 컴퓨터에 정보를 저장하는 방법이에요. 마치 노트에 메모를 적어두는 것과 같아요!

  • 텍스트 파일: 사람이 읽을 수 있는 글자로 된 파일 (.txt, .py, .html)
  • 바이너리 파일: 컴퓨터만 이해할 수 있는 파일 (이미지, 동영상)

오늘은 텍스트 파일을 다뤄볼게요!

🔑 파일 열고 닫기

기본 방법

# 파일 열기 file = open("hello.txt", "r") # r = read(읽기) 모드 # 파일 내용 읽기 content = file.read() print(content) # 파일 닫기 (중요!) file.close()

파일을 열었으면 반드시 닫아야 해요! 문을 열고 나갔으면 닫는 것처럼요.

🌟 with 문 사용하기 (추천!)

# with 문을 사용하면 자동으로 파일을 닫아줘요 with open("hello.txt", "r") as file: content = file.read() print(content) # 여기서 파일이 자동으로 닫혀요!

📖 파일 읽기 방법들

1. 전체 내용 한 번에 읽기

with open("story.txt", "r", encoding="utf-8") as file: # 파일 전체를 하나의 문자열로 all_content = file.read() print(all_content)

2. 한 줄씩 읽기

with open("todo.txt", "r", encoding="utf-8") as file: # 한 줄씩 읽어서 처리 for line in file: print(f"할 일: {line.strip()}") # strip()으로 줄바꿈 제거

3. 모든 줄을 리스트로 읽기

with open("shopping.txt", "r", encoding="utf-8") as file: # 모든 줄을 리스트로 lines = file.readlines() print(f"총 {len(lines)}개의 항목이 있어요!") for i, item in enumerate(lines): print(f"{i+1}. {item.strip()}")

🌏 한글 파일 읽기

한글이 포함된 파일을 읽을 때는 encoding="utf-8"을 꼭 추가해요!

# 한글 파일 읽기 with open("일기.txt", "r", encoding="utf-8") as file: diary = file.read() print(diary)

💡 실용적인 예제

단어 개수 세기

def count_words(filename): """파일의 단어 개수를 세는 함수""" try: with open(filename, "r", encoding="utf-8") as file: content = file.read() words = content.split() return len(words) except FileNotFoundError: print(f"{filename} 파일을 찾을 수 없어요!") return 0 # 사용 예시 word_count = count_words("essay.txt") print(f"단어 개수: {word_count}개")

특정 단어 찾기

def find_word_in_file(filename, search_word): """파일에서 특정 단어가 있는 줄을 찾는 함수""" found_lines = [] try: with open(filename, "r", encoding="utf-8") as file: for line_num, line in enumerate(file, 1): if search_word in line: found_lines.append((line_num, line.strip())) except FileNotFoundError: print(f"{filename} 파일을 찾을 수 없어요!") return found_lines # 사용 예시 results = find_word_in_file("book.txt", "파이썬") for line_num, line in results: print(f"{line_num}번째 줄: {line}")

💡 퀴즈: 파일 읽기 이해도 체크

Q1. 다음 코드의 문제점은 무엇일까요?

file = open("data.txt", "r") content = file.read() print(content) # 뭔가 빠진 것 같은데...

💡 정답 확인

정답: 파일을 닫지 않았어요!

파일을 열었으면 반드시 file.close()로 닫아야 해요. 더 좋은 방법은 with 문을 사용하는 거예요!

with open("data.txt", "r") as file: content = file.read() print(content) # 자동으로 닫혀요!

Q2. 파일을 한 줄씩 읽는 방법은?

  1. file.read()
  2. file.readline()
  3. for line in file:
  4. 2번과 3번 모두

💡 정답 확인

정답: 4번

  • file.readline(): 한 번에 한 줄만 읽기
  • for line in file:: 반복문으로 한 줄씩 읽기
  • 둘 다 한 줄씩 읽는 방법이에요!

✅ 텍스트 파일 읽기 마스터 체크리스트

✅ 텍스트 파일 읽기 마스터 체크리스트

🚀 다음 단계

파일 읽기를 마스터했나요? 이제 파일에 데이터를 저장하는 방법을 배워볼게요!

Last updated on