학습 목표

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

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

댓글 남기기

  • **Nuclear Disarmament Talks Stall Amid US-Greenland Tensions**

    Tensions between the United States and Greenland are escalating as nuclear disarmament talks stall. The situation is further complicated by a recent proposal from the Trump administration to deploy intermediate-range missiles in the region. The lack of progress in nuclear disarmament talks has raised concerns about the stability of international relations. The US, under the…

  • The Uncertain Fate of Yoon Seok-yeol: A Nation Held Hostage by a Presidential Trial

    The trial of President Yoon Seok-yeol has been ongoing for months, leaving the nation in limbo. As the special prosecutor’s office prepares to present its findings, one question remains: will Yoon face the death penalty or life imprisonment? The uncertainty surrounding his fate has sparked intense debate and anxiety among Koreans. The trial began as…

  • The State of Healthcare in Korea: A Path to Normalization

    The Korean healthcare system has been facing significant challenges in recent years. From a crisis point to a path towards normalization, the journey ahead will be crucial for the country’s health sector. In 2022, the healthcare system was at an all-time low, with long waiting times, inadequate medical equipment, and a severe shortage of medical…

  • **Western Countries Express Concern Over Russian Tanker Sinking**

    The recent sinking of a Russian tanker in the Barents Sea has sparked concerns among Western countries over potential implications for global energy markets. The incident raises questions about the security of international shipping lanes and the role of Russia’s military presence in the region. Several reports have emerged indicating that the Russian tanker, which…

  • **Xi Jinping’s Unexpected Gift to South Korea**

    In a surprising move, Chinese President Xi Jinping recently gifted South Korean President Yoon Suk-yup with an electric bicycle. The gesture has been interpreted as a sign of goodwill between the two nations, but it also highlights the complexities of their relationship. The incident took place during a meeting between the two leaders in Seoul,…

← 뒤로

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

TechTinkerer's에서 더 알아보기

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

계속 읽기

TechTinkerer's에서 더 알아보기

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

계속 읽기