학습 목표

  • 파일을 열고, 내용을 읽거나 쓸 수 있다.
  • open(), read(), write(), close() 등의 함수를 사용할 수 있다.
  • 텍스트 파일을 활용한 간단한 프로그램을 만들 수 있다.

파일 입출력의 기초

10.1 파일 열기와 쓰기

file = open("hello.txt", "w")
file.write("Hello, Python!\n")
file.write("파일 쓰기 연습 중입니다.")
file.close()
  • w는 쓰기 모드 (write)
  • \n은 줄바꿈 문자

실습 1: 나의 소개 저장하기

문제: 자신의 이름과 좋아하는 음식 3개를 파일에 저장해보세요. (파일명: my_intro.txt)

모범답안:

f = open("my_intro.txt", "w")
f.write("이름: 주연\n")
f.write("좋아하는 음식: 김밥, 떡볶이, 치킨")
f.close()

해설:

  • 텍스트 파일로 데이터를 저장할 수 있으며 줄바꿈 기호로 구분

10.2 파일 읽기

file = open("hello.txt", "r")
content = file.read()
print(content)
file.close()
  • r은 읽기 모드 (read)

실습 2: 나의 소개 불러오기

문제: 이전에 저장한 my_intro.txt 파일을 읽어 화면에 출력해보세요.

모범답안:

f = open("my_intro.txt", "r")
data = f.read()
print(data)
f.close()

해설:

  • 저장된 텍스트 내용을 다시 읽어 변수에 담고 출력 가능

10.3 with문으로 안전하게 파일 열기

with open("hello.txt", "r") as file:
    print(file.read())
  • with문을 사용하면 close() 생략 가능
  • 파일 작업이 끝나면 자동으로 닫힘

실습 3: with 문으로 읽기

문제: my_intro.txtwith 문으로 읽어보세요.

모범답안:

with open("my_intro.txt", "r") as f:
    print(f.read())

해설:

  • with는 파일 작업 시 안전하고 편리한 방법

파일 입출력 응용

10.4 한 줄씩 읽기 (readline / readlines)

with open("hello.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())
  • readlines()는 줄 단위로 리스트 반환
  • strip()은 줄 끝의 \n 제거

실습 4: 좋아하는 영화 목록 불러오기

문제: movies.txt 파일을 만들고 영화 3개를 저장한 후, 한 줄씩 읽어 출력하세요.

모범답안:

# 파일 저장
with open("movies.txt", "w") as f:
    f.write("인터스텔라\n인셉션\n라라랜드")

# 파일 읽기
with open("movies.txt", "r") as f:
    for line in f:
        print("영화:", line.strip())

해설:

  • 파일을 쓰고 다시 읽으며 반복문 활용 가능

10.5 파일 덧붙이기 (append)

with open("log.txt", "a") as f:
    f.write("새로운 로그 기록입니다.\n")
  • a는 append 모드 → 기존 내용 뒤에 덧붙임

실습 5: 일기 쓰기

문제: diary.txt에 오늘 날짜와 한 줄 일기를 덧붙이세요.

모범답안:

with open("diary.txt", "a") as f:
    f.write("2025-07-03: 오늘 파이썬 수업을 들었다.\n")

해설:

  • 여러 번 실행하면 일기가 계속 누적 저장됨

10.6 파일 입출력 종합 실습

실습 6: 성적 기록 프로그램

문제: 사용자로부터 이름과 점수를 입력받아 scores.txt에 저장하고, 모든 성적을 읽어 출력하세요.

모범답안:

# 입력받아 저장
with open("scores.txt", "a") as f:
    name = input("이름 입력: ")
    score = input("점수 입력: ")
    f.write(f"{name}: {score}\n")

# 저장된 성적 읽기
with open("scores.txt", "r") as f:
    print("--- 성적 목록 ---")
    print(f.read())

해설:

  • 사용자 입력을 받아 파일에 저장하고 다시 출력하는 실전 예제

마무리 퀴즈 & 정리

  1. open("파일명", "w")는 어떤 역할을 하나요? → 쓰기 모드로 파일을 열어 내용을 저장함
  2. read()readlines()의 차이는? → 전체 읽기 vs 줄 단위 읽기
  3. 덧붙이기 모드로 파일을 열려면 어떤 모드를 써야 할까요? → “a” 모드

다음 시간 예고

간단한 텍스트 기반 프로젝트를 만들어보고 지금까지 배운 내용을 종합 복습해볼 거예요!


TechTinkerer's에서 더 알아보기

구독을 신청하면 최신 게시물을 이메일로 받아볼 수 있습니다.

댓글 남기기

  • Introduction to Data Science Concepts in C++

    [Tutorial] · 2026-01-13 23:41 UTC Introduction to Data Science Concepts in C++ 💡 TL;DR Explore fundamental data science concepts like arrays, strings, and basic math functions in C++, opening doors to practical data manipulation tasks. 📚 Learning Objectives This tutorial provides an introduction to key data science concepts in C++, including arrays, strings, and mathematical…

  • Building a Simple Game in C++: Beginner’s Guide to Object Oriented Programming and Graphic Design

    [Tutorial] · 2026-01-13 23:20 UTC Building a Simple Game in C++: Beginner’s Guide to Object Oriented Programming and Graphic Design 💡 TL;DR Learn how to create basic games using C++ by exploring object-oriented programming and drawing on the screen! 📚 Learning Objectives This tutorial will introduce beginners to game development using C++, covering basic programming…

  • Unveiling C++’s Power for Data Science

    [Tutorial] · 2026-01-13 08:25 UTC Unveiling C++’s Power for Data Science 💡 TL;DR Discover how to manipulate data efficiently using C++’s array, string, and math features for impactful data-driven solutions. 📚 Learning Objectives This tutorial introduces fundamental C++ concepts crucial for data science applications, focusing on arrays, strings, and mathematical functions. 🎯 Key Concepts Arrays…

  • Mastering OOP Principles Through Hands-On Game Development

    [Tutorial] · 2026-01-13 08:18 UTC Mastering OOP Principles Through Hands-On Game Development 💡 TL;DR Learn object-oriented programming principles through hands-on game development, focusing on core concepts and building iconic games like Snake or Tetris. 📚 학습 목표 This tutorial introduces Object-Oriented Programming (OOP) by guiding you in creating a classic game like Snake or Tetris.…

  • C++ 기초 다지기: 변수, 연산자, 루프, 조건문, 함수 배우기

    [튜토리얼] · 2026-01-13 08:03 UTC C++ 기초 다지기: 변수, 연산자, 루프, 조건문, 함수 배우기 💡 TL;DR 이 튜토리얼은 C++의 기본적인 개념들을 설명하고 코드 예제를 활용해 실제로 배우는 방법을 제시합니다. 📚 학습 목표 본 튜토리얼은 초보자에게 C++ 프로그래밍의 기본적인 개념을 가르치고 있습니다. 변수와 연산자, 루프, 조건문, 함수 등 기초 원칙을 소개하며 실제 코드 예제를 통해 이론을…

← 뒤로

응답해 주셔서 감사합니다. ✨

TechTinkerer's에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기

TechTinkerer's에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

계속 읽기