본문 바로가기
IT/Python Basic

[Python] 초급 퀴즈16 - 파일 입출력 (open, with, read/write)

by Echinacea 2025. 2. 19.
반응형

 

 

🔹 문제 1: 파일 읽기

다음 코드 실행 시 출력 결과를 예측하세요.

with open("test.txt", "w") as f:
    f.write("Hello, Python!")

with open("test.txt", "r") as f:
    content = f.read()
    print(content)

A) Hello, Python!

B) FileNotFoundError 발생

C) None

D) SyntaxError 발생


 

 

🔹 문제 2: 파일 쓰기 모드

다음 코드 실행 후 test.txt의 내용은?

with open("test.txt", "w") as f:
    f.write("Line 1\n")
    f.write("Line 2\n")

with open("test.txt", "w") as f:
    f.write("New Content\n")

A)

Line 1
Line 2

B)

New Content

C)

Line 1
Line 2
New Content

D)

Error 발생

 

 

🔹 문제 3: append 모드

다음 코드 실행 후 test.txt의 내용은?

with open("test.txt", "w") as f:
    f.write("Start\n")

with open("test.txt", "a") as f:
    f.write("Append this line\n")

A)

Start

B)

Append this line

C)

Start
Append this line

D)

Error 발생

 

 

 

 

 

 

🔹 정답 및 해설

  1. A) Hello, Python!
    📌 설명: w 모드로 파일을 생성 후 read()로 내용을 읽으면 Hello, Python!이 출력됨.
  2. B) New Content
    📌 설명: w 모드는 기존 내용을 지우고 새 내용을 쓰므로 마지막 write() 실행 후 New Content만 남음.
  3. C) Start\nAppend this line
    📌 설명: a 모드는 기존 내용을 유지한 채 새로운 내용을 추가하므로 Start 다음 줄에 Append this line이 추가됨.

 

반응형

댓글