학습 목표

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

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

댓글 남기기

  • Here are 10 programming tutorials, suitable for beginners to

    [튜토리얼] · 2026-01-12 01:01 UTC Here are 10 programming tutorials, suitable for beginners to 📚 학습 목표 데이터 분석은 요즘 매우 중요한 분야입니다. 구글 검색, 마케팅 데이터 분석 등 다양한 분야에서 사용되는데, Python을 통해 이러한 작업을 수행할 수 있는 것은 큰 도움이 됩니다 🎯 핵심 개념 Python과 데이터 분석에 대한 이해를 위한 단계별 가이드 제공…

  • *Real-time Data Visualization with Python and D3.js:** Learn

  • **Iran Protests Turn Deadly as Death Toll Surges**

    The situation in Iran has taken a deadly turn as protests against the government continue to escalate. The death toll has risen significantly, with over 60 protesters reported to have died since the demonstrations began. The Iranian authorities have responded by tightening their grip on the internet and warning of severe consequences for those who…

  • The Chaebum Conspiracy: A Web of Intrigue Surrounding Yoon Seok-yeol’s Election

    The 2022 South Korean presidential election has been marred by controversy and scandal, with one figure at the center of it all being Yoon Seok-yeol. As a key witness in the impeachment trial against him, Chaebum Lee has shed light on the inner workings of the group that allegedly orchestrated his rise to power. The…

  • **North Korea Threatens to Shoot Down South Korean Drones Again**

    A recent statement from North Korean officials has raised concerns about the safety of drone operations over the Demilitarized Zone (DMZ) between North and South Korea. The country’s military claimed that it will take action if South Korean drones enter its airspace again, sparking fears of a potential conflict. The tensions surrounding drone flights over…

← 뒤로

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

TechTinkerer's에서 더 알아보기

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

계속 읽기

TechTinkerer's에서 더 알아보기

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

계속 읽기