Text files · 텍스트 파일
Files keep data
- Variables vanish when a program ends; a file stores data so it lasts.
- The exam covers reading from and writing to text files.
- Work in three steps: open, read or write, then close.
파일은 데이터를 저장합니다
- 변수는 프로그램 종료 시 사라지지만, 파일(file) 에 저장하면 데이터가 지속됩니다.
- 시험에서는 텍스트 파일(text files) 로부터 읽기 및 쓰기 내용을 다룹니다.
- 세 단계로 작업합니다: 열기(open), 읽기 또는 쓰기, 그리고 닫기(close).
Writing to a file
open(name, "w")opens a file for writing ("w"overwrites what was there).withcloses the file automatically when the block ends.\nstarts a new line in the file.
파일에 쓰기
open(name, "w")는 파일의 쓰기(write) 모드로 엽니다 ("w"는 기존 내용을 덮어 씌움).with는 블록이 끝나면 파일을 자동으로 닫습니다.\n는 파일 내에서 새로운 줄을 시작합니다.
with open("notes.txt", "w") as f:
f.write("Hello\n")
f.write("World\n")
Reading a file
open(name, "r")opens a file for reading..read()pulls in the whole contents as one string.
파일 읽기
open(name, "r")는 파일의 읽기(read) 모드로 엽니다..read()는 전체 내용을 하나의 문자열로 가져옵니다.
with open("notes.txt", "r") as f:
text = f.read()
print(text)
Reading line by line
- Looping over the file gives one line at a time — handy for totalling or counting.
줄 단위로 읽기
- 파일에 대해 루프를 돌리면 줄 단위(one line at a time) 로 처리되며, 합계 계산이나 카운팅에 유용합니다.
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
In the exam: file handling
- Pseudocode opens a file for a mode, reads or writes, then closes it.
시험 준비: 파일 처리
- 가구문(mode)으로 파일을 열고, 읽거나 쓴 뒤, 닫습니다.
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
Common mistakes
- Open, then read or write, then close the file.
- A line you read still carries its newline character.
흔한 실수
- 열고, 읽고(또는 쓰고), 그리고 파일을 닫습니다(close).
- 읽은 줄에는 여전히 개행 문자(newline character)가 포함됩니다.
Now you try
- Write a file, then open it again to read it back.
- Press Check answer to test your code.
이제 직접 해보기
- 파일을 쓴 후 다시 열어서 읽어오세요.
- Answer 확인 버튼을 눌러 코드를 테스트하세요.
Using a file · 파일 사용하기
A file is used in three steps: open, read or write, close. · 파일 사용은 세 단계로 이루어집니다: 열기, 읽기 또는 쓰기, 닫기.
In one run: write the line Cambridge to a file called school.txt, then open it again, read it, and print what you read. · 한 번의 실행에서: 줄 Cambridge을 파일 school.txt에 쓴 다음, 파일을 다시 열고, 읽고, 읽은 내용을 print하세요.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
The starter writes three lines to a file. Read it back and count the lines with a loop. Store the count in count (the answer is 3). · 시작 프로그램은 파일에 세 줄을 씁니다. 이를 다시 읽고 루프를 사용하여 줄의 개수를 세세요. 개수를 변수 count에 저장하세요 (정답은 3).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
The starter writes 10, 20, 30 to a file, one per line. Read them back, convert each line with int(...), and add them up in total (the answer is 60). · 시작 프로그램은 integers 10, 20, 30를 파일에 줄마다 하나씩 씁니다.これらを 다시 읽고 각 줄을 int(...)으로 변환한 후, их 합을 변수 total에 저장하세요 (정답은 60).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.