학습 목표

  • 파일을 열고, 내용을 읽거나 쓸 수 있다.
  • 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에서 더 알아보기

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

댓글 남기기

  • Understanding Pointers and Memory Management in C++

    [Tutorial] · 2026-04-30 05:10 UTC Understanding Pointers and Memory Management in C++ 💡 TL;DR Mastering pointers in C++ is crucial for efficient memory management and writing effective code. 📚 Learning Objectives This tutorial covers the fundamentals of pointers in C++, including declaration, initialization, and memory management. Students will learn how to effectively use pointers to…

  • Building a Command-Line Calculator with C++

    [Tutorial] · 2026-04-30 04:08 UTC Building a Command-Line Calculator with C++ 💡 TL;DR Learn how to build a command-line calculator in C++ that takes user input and performs basic arithmetic operations. 📚 Learning Objectives This tutorial guides you through creating a basic command-line calculator in C++. You’ll learn how to take user input, perform arithmetic…

  • Mastering Python Data Structures for Efficient Coding

    [Tutorial] · 2026-04-30 03:05 UTC Mastering Python Data Structures for Efficient Coding 💡 TL;DR Learn about Python’s fundamental data structures – arrays, lists, tuples, and dictionaries – to write efficient and scalable code. 📚 Learning Objectives This tutorial covers the essential Python data structures – arrays, lists, tuples, and dictionaries. You’ll learn about their usage,…

  • Introduction to Object-Oriented Programming in Python

    [Tutorial] · 2026-04-30 02:02 UTC Introduction to Object-Oriented Programming in Python 💡 TL;DR Learn the fundamentals of object-oriented programming in Python, including classes and objects, inheritance, and polymorphism. 📚 Learning Objectives This tutorial introduces the basics of object-oriented programming in Python, covering classes, objects, inheritance, and polymorphism. By the end of this tutorial, beginners will…

  • Complete Guide to Python List Comprehensions

    [Tutorial] · 2026-04-30 01:00 UTC Complete Guide to Python List Comprehensions 💡 TL;DR Master Python list comprehensions to write concise and efficient code for data manipulation and transformation tasks. 📚 Learning Objectives This tutorial covers the basics of Python list comprehensions, including syntax, use cases, and execution results. You’ll learn how to write efficient and…

← 뒤로

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

TechTinkerer's에서 더 알아보기

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

계속 읽기

TechTinkerer's에서 더 알아보기

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

계속 읽기